blob: 33766f9a79653d31fbdc088d3a14705b6a98a2ee [file] [log] [blame]
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor94b1dd22008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000022#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000023#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000025#include "llvm/Support/Compiler.h"
26#include <algorithm>
Torok Edwinf42e4a62009-08-24 13:25:12 +000027#include <cstdio>
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000028
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
41 ICC_Qualification_Adjustment,
42 ICC_Promotion,
43 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000044 ICC_Promotion,
45 ICC_Conversion,
46 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000047 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000052 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000053 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000054 ICC_Conversion
55 };
56 return Category[(int)Kind];
57}
58
59/// GetConversionRank - Retrieve the implicit conversion rank
60/// corresponding to the given implicit conversion kind.
61ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
62 static const ImplicitConversionRank
63 Rank[(int)ICK_Num_Conversion_Kinds] = {
64 ICR_Exact_Match,
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Promotion,
70 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000071 ICR_Promotion,
72 ICR_Conversion,
73 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000074 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000079 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000080 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000081 ICR_Conversion
82 };
83 return Rank[(int)Kind];
84}
85
86/// GetImplicitConversionName - Return the name of this kind of
87/// implicit conversion.
88const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
89 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
90 "No conversion",
91 "Lvalue-to-rvalue",
92 "Array-to-pointer",
93 "Function-to-pointer",
94 "Qualification",
95 "Integral promotion",
96 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +000097 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000098 "Integral conversion",
99 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000100 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000101 "Floating-integral conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000102 "Complex-real conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000103 "Pointer conversion",
104 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000105 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000106 "Compatible-types conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000107 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000108 };
109 return Name[Kind];
110}
111
Douglas Gregor60d62c22008-10-31 16:23:19 +0000112/// StandardConversionSequence - Set the standard conversion
113/// sequence to the identity conversion.
114void StandardConversionSequence::setAsIdentityConversion() {
115 First = ICK_Identity;
116 Second = ICK_Identity;
117 Third = ICK_Identity;
118 Deprecated = false;
119 ReferenceBinding = false;
120 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000121 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000122 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000123}
124
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000125/// getRank - Retrieve the rank of this standard conversion sequence
126/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
127/// implicit conversions.
128ImplicitConversionRank StandardConversionSequence::getRank() const {
129 ImplicitConversionRank Rank = ICR_Exact_Match;
130 if (GetConversionRank(First) > Rank)
131 Rank = GetConversionRank(First);
132 if (GetConversionRank(Second) > Rank)
133 Rank = GetConversionRank(Second);
134 if (GetConversionRank(Third) > Rank)
135 Rank = GetConversionRank(Third);
136 return Rank;
137}
138
139/// isPointerConversionToBool - Determines whether this conversion is
140/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000141/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000142/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000143bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000144 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
145 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
146
147 // Note that FromType has not necessarily been transformed by the
148 // array-to-pointer or function-to-pointer implicit conversions, so
149 // check for their presence as well as checking whether FromType is
150 // a pointer.
151 if (ToType->isBooleanType() &&
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000152 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000153 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154 return true;
155
156 return false;
157}
158
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000159/// isPointerConversionToVoidPointer - Determines whether this
160/// conversion is a conversion of a pointer to a void pointer. This is
161/// used as part of the ranking of standard conversion sequences (C++
162/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000163bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000166 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 Kremenek6217b802009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor8e9bebd2008-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 Gregor225c41e2008-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 Gregor8e9bebd2008-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 Lattnerd9d22dd2008-11-24 05:29:24 +0000227 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor8e9bebd2008-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
Mike Stump1eb44332009-09-09 15:08:12 +0000263// FunctionDecl that New cannot be overloaded with.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000264//
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",
Mike Stump1eb44332009-09-09 15:08:12 +0000272// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000273//
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
Mike Stump1eb44332009-09-09 15:08:12 +0000286Sema::IsOverload(FunctionDecl *New, Decl* OldD,
287 OverloadedFunctionDecl::function_iterator& MatchedDecl) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000288 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
289 // Is this new function an overload of every function in the
290 // overload set?
291 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
292 FuncEnd = Ovl->function_end();
293 for (; Func != FuncEnd; ++Func) {
294 if (!IsOverload(New, *Func, MatchedDecl)) {
295 MatchedDecl = Func;
296 return false;
297 }
298 }
299
300 // This function overloads every function in the overload set.
301 return true;
Douglas Gregore53060f2009-06-25 22:08:12 +0000302 } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
303 return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
304 else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000305 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +0000306 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
307
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000308 // C++ [temp.fct]p2:
309 // A function template can be overloaded with other function templates
310 // and with normal (non-template) functions.
311 if ((OldTemplate == 0) != (NewTemplate == 0))
312 return true;
313
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000314 // Is the function New an overload of the function Old?
315 QualType OldQType = Context.getCanonicalType(Old->getType());
316 QualType NewQType = Context.getCanonicalType(New->getType());
317
318 // Compare the signatures (C++ 1.3.10) of the two functions to
319 // determine whether they are overloads. If we find any mismatch
320 // in the signature, they are overloads.
321
322 // If either of these functions is a K&R-style function (no
323 // prototype), then we consider them to have matching signatures.
Douglas Gregor72564e72009-02-26 23:50:07 +0000324 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
325 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000326 return false;
327
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000328 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
329 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000330
331 // The signature of a function includes the types of its
332 // parameters (C++ 1.3.10), which includes the presence or absence
333 // of the ellipsis; see C++ DR 357).
334 if (OldQType != NewQType &&
335 (OldType->getNumArgs() != NewType->getNumArgs() ||
336 OldType->isVariadic() != NewType->isVariadic() ||
337 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
338 NewType->arg_type_begin())))
339 return true;
340
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000341 // C++ [temp.over.link]p4:
Mike Stump1eb44332009-09-09 15:08:12 +0000342 // The signature of a function template consists of its function
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000343 // signature, its return type and its template parameter list. The names
344 // of the template parameters are significant only for establishing the
Mike Stump1eb44332009-09-09 15:08:12 +0000345 // relationship between the template parameters and the rest of the
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000346 // signature.
347 //
348 // We check the return type and template parameter lists for function
349 // templates first; the remaining checks follow.
350 if (NewTemplate &&
Mike Stump1eb44332009-09-09 15:08:12 +0000351 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
352 OldTemplate->getTemplateParameters(),
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000353 false, false, SourceLocation()) ||
354 OldType->getResultType() != NewType->getResultType()))
355 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000357 // If the function is a class member, its signature includes the
358 // cv-qualifiers (if any) on the function itself.
359 //
360 // As part of this, also check whether one of the member functions
361 // is static, in which case they are not overloads (C++
362 // 13.1p2). While not part of the definition of the signature,
363 // this check is important to determine whether these functions
364 // can be overloaded.
365 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
366 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Mike Stump1eb44332009-09-09 15:08:12 +0000367 if (OldMethod && NewMethod &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000368 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor1ca50c32008-11-21 15:36:28 +0000369 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000370 return true;
371
372 // The signatures match; this is not an overload.
373 return false;
374 } else {
375 // (C++ 13p1):
376 // Only function declarations can be overloaded; object and type
377 // declarations cannot be overloaded.
378 return false;
379 }
380}
381
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000382/// TryImplicitConversion - Attempt to perform an implicit conversion
383/// from the given expression (Expr) to the given type (ToType). This
384/// function returns an implicit conversion sequence that can be used
385/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000386///
387/// void f(float f);
388/// void g(int i) { f(i); }
389///
390/// this routine would produce an implicit conversion sequence to
391/// describe the initialization of f from i, which will be a standard
392/// conversion sequence containing an lvalue-to-rvalue conversion (C++
393/// 4.1) followed by a floating-integral conversion (C++ 4.9).
394//
395/// Note that this routine only determines how the conversion can be
396/// performed; it does not actually perform the conversion. As such,
397/// it will not produce any diagnostics if no conversion is available,
398/// but will instead return an implicit conversion sequence of kind
399/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000400///
401/// If @p SuppressUserConversions, then user-defined conversions are
402/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000403/// If @p AllowExplicit, then explicit user-defined conversions are
404/// permitted.
Sebastian Redle2b68332009-04-12 17:16:29 +0000405/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
406/// no matter its actual lvalueness.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000407ImplicitConversionSequence
Anders Carlsson2974b5c2009-08-27 17:14:02 +0000408Sema::TryImplicitConversion(Expr* From, QualType ToType,
409 bool SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +0000410 bool AllowExplicit, bool ForceRValue,
Mike Stump1eb44332009-09-09 15:08:12 +0000411 bool InOverloadResolution) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000412 ImplicitConversionSequence ICS;
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +0000413 OverloadCandidateSet Conversions;
Anders Carlsson08972922009-08-28 15:33:32 +0000414 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor60d62c22008-10-31 16:23:19 +0000415 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000416 else if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +0000417 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +0000418 Conversions,
Sebastian Redle2b68332009-04-12 17:16:29 +0000419 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +0000420 ForceRValue) == OR_Success) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000421 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000422 // C++ [over.ics.user]p4:
423 // A conversion of an expression of class type to the same class
424 // type is given Exact Match rank, and a conversion of an
425 // expression of class type to a base class of that type is
426 // given Conversion rank, in spite of the fact that a copy
427 // constructor (i.e., a user-defined conversion function) is
428 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000429 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000430 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000431 QualType FromCanon
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000432 = Context.getCanonicalType(From->getType().getUnqualifiedType());
433 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
434 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000435 // Turn this into a "standard" conversion sequence, so that it
436 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000437 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
438 ICS.Standard.setAsIdentityConversion();
439 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
440 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000441 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000442 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000443 ICS.Standard.Second = ICK_Derived_To_Base;
444 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000445 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000446
447 // C++ [over.best.ics]p4:
448 // However, when considering the argument of a user-defined
449 // conversion function that is a candidate by 13.3.1.3 when
450 // invoked for the copying of the temporary in the second step
451 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
452 // 13.3.1.6 in all cases, only standard conversion sequences and
453 // ellipsis conversion sequences are allowed.
454 if (SuppressUserConversions &&
455 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
456 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000457 } else
Douglas Gregor60d62c22008-10-31 16:23:19 +0000458 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000459
460 return ICS;
461}
462
463/// IsStandardConversion - Determines whether there is a standard
464/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
465/// expression From to the type ToType. Standard conversion sequences
466/// only consider non-class types; for conversions that involve class
467/// types, use TryImplicitConversion. If a conversion exists, SCS will
468/// contain the standard conversion sequence required to perform this
469/// conversion and this routine will return true. Otherwise, this
470/// routine will return false and the value of SCS is unspecified.
Mike Stump1eb44332009-09-09 15:08:12 +0000471bool
472Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000473 bool InOverloadResolution,
Mike Stump1eb44332009-09-09 15:08:12 +0000474 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000475 QualType FromType = From->getType();
476
Douglas Gregor60d62c22008-10-31 16:23:19 +0000477 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000478 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000479 SCS.Deprecated = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000480 SCS.IncompatibleObjC = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000481 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000482 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000483
Douglas Gregorf9201e02009-02-11 23:02:49 +0000484 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000485 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000486 if (FromType->isRecordType() || ToType->isRecordType()) {
487 if (getLangOptions().CPlusPlus)
488 return false;
489
Mike Stump1eb44332009-09-09 15:08:12 +0000490 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000491 }
492
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000493 // The first conversion can be an lvalue-to-rvalue conversion,
494 // array-to-pointer conversion, or function-to-pointer conversion
495 // (C++ 4p1).
496
Mike Stump1eb44332009-09-09 15:08:12 +0000497 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000498 // An lvalue (3.10) of a non-function, non-array type T can be
499 // converted to an rvalue.
500 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000501 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000502 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000503 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000504 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000505
506 // If T is a non-class type, the type of the rvalue is the
507 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000508 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
509 // just strip the qualifiers because they don't matter.
510
511 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregor60d62c22008-10-31 16:23:19 +0000512 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000513 } else if (FromType->isArrayType()) {
514 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000515 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000516
517 // An lvalue or rvalue of type "array of N T" or "array of unknown
518 // bound of T" can be converted to an rvalue of type "pointer to
519 // T" (C++ 4.2p1).
520 FromType = Context.getArrayDecayedType(FromType);
521
522 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
523 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000524 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000525
526 // For the purpose of ranking in overload resolution
527 // (13.3.3.1.1), this conversion is considered an
528 // array-to-pointer conversion followed by a qualification
529 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000530 SCS.Second = ICK_Identity;
531 SCS.Third = ICK_Qualification;
532 SCS.ToTypePtr = ToType.getAsOpaquePtr();
533 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000534 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000535 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
536 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000537 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000538
539 // An lvalue of function type T can be converted to an rvalue of
540 // type "pointer to T." The result is a pointer to the
541 // function. (C++ 4.3p1).
542 FromType = Context.getPointerType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000543 } else if (FunctionDecl *Fn
Douglas Gregor904eed32008-11-10 20:40:00 +0000544 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000545 // Address of overloaded function (C++ [over.over]).
Douglas Gregor904eed32008-11-10 20:40:00 +0000546 SCS.First = ICK_Function_To_Pointer;
547
548 // We were able to resolve the address of the overloaded function,
549 // so we can convert to the type of that function.
550 FromType = Fn->getType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000551 if (ToType->isLValueReferenceType())
552 FromType = Context.getLValueReferenceType(FromType);
553 else if (ToType->isRValueReferenceType())
554 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000555 else if (ToType->isMemberPointerType()) {
556 // Resolve address only succeeds if both sides are member pointers,
557 // but it doesn't have to be the same class. See DR 247.
558 // Note that this means that the type of &Derived::fn can be
559 // Ret (Base::*)(Args) if the fn overload actually found is from the
560 // base class, even if it was brought into the derived class via a
561 // using declaration. The standard isn't clear on this issue at all.
562 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
563 FromType = Context.getMemberPointerType(FromType,
564 Context.getTypeDeclType(M->getParent()).getTypePtr());
565 } else
Douglas Gregor904eed32008-11-10 20:40:00 +0000566 FromType = Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000567 } else {
568 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000569 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000570 }
571
572 // The second conversion can be an integral promotion, floating
573 // point promotion, integral conversion, floating point conversion,
574 // floating-integral conversion, pointer conversion,
575 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000576 // For overloading in C, this can also be a "compatible-type"
577 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000578 bool IncompatibleObjC = false;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000579 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000580 // The unqualified versions of the types are the same: there's no
581 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000582 SCS.Second = ICK_Identity;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000583 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000584 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000585 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000586 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000587 } else if (IsFloatingPointPromotion(FromType, ToType)) {
588 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000589 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000590 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000591 } else if (IsComplexPromotion(FromType, ToType)) {
592 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000593 SCS.Second = ICK_Complex_Promotion;
594 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000595 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000596 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000597 // Integral conversions (C++ 4.7).
598 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000599 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000600 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000601 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
602 // Floating point conversions (C++ 4.8).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000603 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000604 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000605 } else if (FromType->isComplexType() && ToType->isComplexType()) {
606 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000607 SCS.Second = ICK_Complex_Conversion;
608 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000609 } else if ((FromType->isFloatingType() &&
610 ToType->isIntegralType() && (!ToType->isBooleanType() &&
611 !ToType->isEnumeralType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000612 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000613 ToType->isFloatingType())) {
614 // Floating-integral conversions (C++ 4.9).
615 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000616 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000617 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000618 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
619 (ToType->isComplexType() && FromType->isArithmeticType())) {
620 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000621 SCS.Second = ICK_Complex_Real;
622 FromType = ToType.getUnqualifiedType();
Anders Carlsson08972922009-08-28 15:33:32 +0000623 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
624 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000625 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000626 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000627 SCS.IncompatibleObjC = IncompatibleObjC;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000628 } else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
629 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000630 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000631 } else if (ToType->isBooleanType() &&
632 (FromType->isArithmeticType() ||
633 FromType->isEnumeralType() ||
634 FromType->isPointerType() ||
635 FromType->isBlockPointerType() ||
636 FromType->isMemberPointerType() ||
637 FromType->isNullPtrType())) {
638 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000639 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000640 FromType = Context.BoolTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000641 } else if (!getLangOptions().CPlusPlus &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000642 Context.typesAreCompatible(ToType, FromType)) {
643 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000644 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000645 } else {
646 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000647 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000648 }
649
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000650 QualType CanonFrom;
651 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000652 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000653 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000654 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000655 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000656 CanonFrom = Context.getCanonicalType(FromType);
657 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000658 } else {
659 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000660 SCS.Third = ICK_Identity;
661
Mike Stump1eb44332009-09-09 15:08:12 +0000662 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +0000663 // [...] Any difference in top-level cv-qualification is
664 // subsumed by the initialization itself and does not constitute
665 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000666 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000667 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000668 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000669 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
670 FromType = ToType;
671 CanonFrom = CanonTo;
672 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000673 }
674
675 // If we have not converted the argument type to the parameter type,
676 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000677 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000678 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000679
Douglas Gregor60d62c22008-10-31 16:23:19 +0000680 SCS.ToTypePtr = FromType.getAsOpaquePtr();
681 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000682}
683
684/// IsIntegralPromotion - Determines whether the conversion from the
685/// expression From (whose potentially-adjusted type is FromType) to
686/// ToType is an integral promotion (C++ 4.5). If so, returns true and
687/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000688bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000689 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000690 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000691 if (!To) {
692 return false;
693 }
Douglas Gregor8e9bebd2008-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 Redl07779722008-10-31 14:43:28 +0000700 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-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.
Mike Stump1eb44332009-09-09 15:08:12 +0000705 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000706 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000707 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000708 }
709
Douglas Gregor8e9bebd2008-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.
Mike Stump1eb44332009-09-09 15:08:12 +0000733 QualType PromoteTypes[6] = {
734 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000735 Context.LongTy, Context.UnsignedLongTy ,
736 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000737 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000738 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000739 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
740 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +0000741 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000742 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 Redl07779722008-10-31 14:43:28 +0000746 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor8e9bebd2008-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 Stump390b4cc2009-05-16 07:39:55 +0000759 // FIXME: We should delay checking of bit-fields until we actually perform the
760 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000761 using llvm::APSInt;
762 if (From)
763 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +0000764 APSInt BitWidth;
Douglas Gregor33bbbc52009-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);
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Douglas Gregor86f19402008-12-20 23:49:58 +0000770 // 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 }
Mike Stump1eb44332009-09-09 15:08:12 +0000775
Douglas Gregor86f19402008-12-20 23:49:58 +0000776 // 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 }
Mike Stump1eb44332009-09-09 15:08:12 +0000781
Douglas Gregor86f19402008-12-20 23:49:58 +0000782 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000783 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000784 }
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Douglas Gregor8e9bebd2008-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 Redl07779722008-10-31 14:43:28 +0000788 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000789 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000790 }
Douglas Gregor8e9bebd2008-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.
Mike Stump1eb44332009-09-09 15:08:12 +0000798bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000799 /// An rvalue of type float can be converted to an rvalue of type
800 /// double. (C++ 4.6p1).
801 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000802 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000803 if (FromBuiltin->getKind() == BuiltinType::Float &&
804 ToBuiltin->getKind() == BuiltinType::Double)
805 return true;
806
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000807 // C99 6.3.1.5p1:
808 // When a float is promoted to double or long double, or a
809 // double is promoted to long double [...].
810 if (!getLangOptions().CPlusPlus &&
811 (FromBuiltin->getKind() == BuiltinType::Float ||
812 FromBuiltin->getKind() == BuiltinType::Double) &&
813 (ToBuiltin->getKind() == BuiltinType::LongDouble))
814 return true;
815 }
816
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000817 return false;
818}
819
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000820/// \brief Determine if a conversion is a complex promotion.
821///
822/// A complex promotion is defined as a complex -> complex conversion
823/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000824/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000825bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
826 const ComplexType *FromComplex = FromType->getAsComplexType();
827 if (!FromComplex)
828 return false;
829
830 const ComplexType *ToComplex = ToType->getAsComplexType();
831 if (!ToComplex)
832 return false;
833
834 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000835 ToComplex->getElementType()) ||
836 IsIntegralPromotion(0, FromComplex->getElementType(),
837 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000838}
839
Douglas Gregorcb7de522008-11-26 23:31:11 +0000840/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
841/// the pointer type FromPtr to a pointer to type ToPointee, with the
842/// same type qualifiers as FromPtr has on its pointee type. ToType,
843/// if non-empty, will be a pointer to ToType that may or may not have
844/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +0000845static QualType
846BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000847 QualType ToPointee, QualType ToType,
848 ASTContext &Context) {
849 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
850 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
851 unsigned Quals = CanonFromPointee.getCVRQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +0000852
853 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregorcb7de522008-11-26 23:31:11 +0000854 if (CanonToPointee.getCVRQualifiers() == Quals) {
855 // ToType is exactly what we need. Return it.
856 if (ToType.getTypePtr())
857 return ToType;
858
859 // Build a pointer to ToPointee. It has the right qualifiers
860 // already.
861 return Context.getPointerType(ToPointee);
862 }
863
864 // Just build a canonical type that has the right qualifiers.
865 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
866}
867
Mike Stump1eb44332009-09-09 15:08:12 +0000868static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000869 bool InOverloadResolution,
870 ASTContext &Context) {
871 // Handle value-dependent integral null pointer constants correctly.
872 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
873 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
874 Expr->getType()->isIntegralType())
875 return !InOverloadResolution;
876
877 return Expr->isNullPointerConstant(Context);
878}
Mike Stump1eb44332009-09-09 15:08:12 +0000879
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000880/// IsPointerConversion - Determines whether the conversion of the
881/// expression From, which has the (possibly adjusted) type FromType,
882/// can be converted to the type ToType via a pointer conversion (C++
883/// 4.10). If so, returns true and places the converted type (that
884/// might differ from ToType in its cv-qualifiers at some level) into
885/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000886///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000887/// This routine also supports conversions to and from block pointers
888/// and conversions with Objective-C's 'id', 'id<protocols...>', and
889/// pointers to interfaces. FIXME: Once we've determined the
890/// appropriate overloading rules for Objective-C, we may want to
891/// split the Objective-C checks into a different routine; however,
892/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000893/// conversions, so for now they live here. IncompatibleObjC will be
894/// set if the conversion is an allowed Objective-C conversion that
895/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000896bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000897 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +0000898 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +0000899 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +0000900 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000901 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
902 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000903
Mike Stump1eb44332009-09-09 15:08:12 +0000904 // Conversion from a null pointer constant to any Objective-C pointer type.
905 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000906 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +0000907 ConvertedType = ToType;
908 return true;
909 }
910
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000911 // Blocks: Block pointers can be converted to void*.
912 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000913 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000914 ConvertedType = ToType;
915 return true;
916 }
917 // Blocks: A null pointer constant can be converted to a block
918 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +0000919 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000920 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000921 ConvertedType = ToType;
922 return true;
923 }
924
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000925 // If the left-hand-side is nullptr_t, the right side can be a null
926 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +0000927 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000928 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000929 ConvertedType = ToType;
930 return true;
931 }
932
Ted Kremenek6217b802009-07-29 21:53:49 +0000933 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000934 if (!ToTypePtr)
935 return false;
936
937 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000938 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000939 ConvertedType = ToType;
940 return true;
941 }
Sebastian Redl07779722008-10-31 14:43:28 +0000942
Douglas Gregorcb7de522008-11-26 23:31:11 +0000943 // Beyond this point, both types need to be pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +0000944 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +0000945 if (!FromTypePtr)
946 return false;
947
948 QualType FromPointeeType = FromTypePtr->getPointeeType();
949 QualType ToPointeeType = ToTypePtr->getPointeeType();
950
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000951 // An rvalue of type "pointer to cv T," where T is an object type,
952 // can be converted to an rvalue of type "pointer to cv void" (C++
953 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +0000954 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000955 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +0000956 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000957 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000958 return true;
959 }
960
Douglas Gregorf9201e02009-02-11 23:02:49 +0000961 // When we're overloading in C, we allow a special kind of pointer
962 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +0000963 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +0000964 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000965 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000966 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +0000967 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +0000968 return true;
969 }
970
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000971 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +0000972 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000973 // An rvalue of type "pointer to cv D," where D is a class type,
974 // can be converted to an rvalue of type "pointer to cv B," where
975 // B is a base class (clause 10) of D. If B is an inaccessible
976 // (clause 11) or ambiguous (10.2) base class of D, a program that
977 // necessitates this conversion is ill-formed. The result of the
978 // conversion is a pointer to the base class sub-object of the
979 // derived class object. The null pointer value is converted to
980 // the null pointer value of the destination type.
981 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000982 // Note that we do not check for ambiguity or inaccessibility
983 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +0000984 if (getLangOptions().CPlusPlus &&
985 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorcb7de522008-11-26 23:31:11 +0000986 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000987 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +0000988 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000989 ToType, Context);
990 return true;
991 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000992
Douglas Gregorc7887512008-12-19 19:13:09 +0000993 return false;
994}
995
996/// isObjCPointerConversion - Determines whether this is an
997/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
998/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +0000999bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001000 QualType& ConvertedType,
1001 bool &IncompatibleObjC) {
1002 if (!getLangOptions().ObjC1)
1003 return false;
1004
Steve Naroff14108da2009-07-10 23:34:53 +00001005 // First, we handle all conversions on ObjC object pointer types.
1006 const ObjCObjectPointerType* ToObjCPtr = ToType->getAsObjCObjectPointerType();
Mike Stump1eb44332009-09-09 15:08:12 +00001007 const ObjCObjectPointerType *FromObjCPtr =
Steve Naroff14108da2009-07-10 23:34:53 +00001008 FromType->getAsObjCObjectPointerType();
Douglas Gregorc7887512008-12-19 19:13:09 +00001009
Steve Naroff14108da2009-07-10 23:34:53 +00001010 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001011 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001012 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001013 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001014 ConvertedType = ToType;
1015 return true;
1016 }
1017 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001018 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001019 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001020 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001021 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001022 ConvertedType = ToType;
1023 return true;
1024 }
1025 // Objective C++: We're able to convert from a pointer to an
1026 // interface to a pointer to a different interface.
1027 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1028 ConvertedType = ToType;
1029 return true;
1030 }
1031
1032 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1033 // Okay: this is some kind of implicit downcast of Objective-C
1034 // interfaces, which is permitted. However, we're going to
1035 // complain about it.
1036 IncompatibleObjC = true;
1037 ConvertedType = FromType;
1038 return true;
1039 }
Mike Stump1eb44332009-09-09 15:08:12 +00001040 }
Steve Naroff14108da2009-07-10 23:34:53 +00001041 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001042 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001043 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001044 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001045 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001046 ToPointeeType = ToBlockPtr->getPointeeType();
1047 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001048 return false;
1049
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001050 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001051 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001052 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001053 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001054 FromPointeeType = FromBlockPtr->getPointeeType();
1055 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001056 return false;
1057
Douglas Gregorc7887512008-12-19 19:13:09 +00001058 // If we have pointers to pointers, recursively check whether this
1059 // is an Objective-C conversion.
1060 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1061 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1062 IncompatibleObjC)) {
1063 // We always complain about this conversion.
1064 IncompatibleObjC = true;
1065 ConvertedType = ToType;
1066 return true;
1067 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001068 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001069 // differences in the argument and result types are in Objective-C
1070 // pointer conversions. If so, we permit the conversion (but
1071 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001072 const FunctionProtoType *FromFunctionType
Douglas Gregor72564e72009-02-26 23:50:07 +00001073 = FromPointeeType->getAsFunctionProtoType();
1074 const FunctionProtoType *ToFunctionType
1075 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregorc7887512008-12-19 19:13:09 +00001076 if (FromFunctionType && ToFunctionType) {
1077 // If the function types are exactly the same, this isn't an
1078 // Objective-C pointer conversion.
1079 if (Context.getCanonicalType(FromPointeeType)
1080 == Context.getCanonicalType(ToPointeeType))
1081 return false;
1082
1083 // Perform the quick checks that will tell us whether these
1084 // function types are obviously different.
1085 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1086 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1087 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1088 return false;
1089
1090 bool HasObjCConversion = false;
1091 if (Context.getCanonicalType(FromFunctionType->getResultType())
1092 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1093 // Okay, the types match exactly. Nothing to do.
1094 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1095 ToFunctionType->getResultType(),
1096 ConvertedType, IncompatibleObjC)) {
1097 // Okay, we have an Objective-C pointer conversion.
1098 HasObjCConversion = true;
1099 } else {
1100 // Function types are too different. Abort.
1101 return false;
1102 }
Mike Stump1eb44332009-09-09 15:08:12 +00001103
Douglas Gregorc7887512008-12-19 19:13:09 +00001104 // Check argument types.
1105 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1106 ArgIdx != NumArgs; ++ArgIdx) {
1107 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1108 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1109 if (Context.getCanonicalType(FromArgType)
1110 == Context.getCanonicalType(ToArgType)) {
1111 // Okay, the types match exactly. Nothing to do.
1112 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1113 ConvertedType, IncompatibleObjC)) {
1114 // Okay, we have an Objective-C pointer conversion.
1115 HasObjCConversion = true;
1116 } else {
1117 // Argument types are too different. Abort.
1118 return false;
1119 }
1120 }
1121
1122 if (HasObjCConversion) {
1123 // We had an Objective-C conversion. Allow this pointer
1124 // conversion, but complain about it.
1125 ConvertedType = ToType;
1126 IncompatibleObjC = true;
1127 return true;
1128 }
1129 }
1130
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001131 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001132}
1133
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001134/// CheckPointerConversion - Check the pointer conversion from the
1135/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001136/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001137/// conversions for which IsPointerConversion has already returned
1138/// true. It returns true and produces a diagnostic if there was an
1139/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001140bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
1141 CastExpr::CastKind &Kind) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001142 QualType FromType = From->getType();
1143
Ted Kremenek6217b802009-07-29 21:53:49 +00001144 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1145 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001146 QualType FromPointeeType = FromPtrType->getPointeeType(),
1147 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001148
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001149 if (FromPointeeType->isRecordType() &&
1150 ToPointeeType->isRecordType()) {
1151 // We must have a derived-to-base conversion. Check an
1152 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001153 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1154 From->getExprLoc(),
1155 From->getSourceRange()))
1156 return true;
1157
1158 // The conversion was successful.
1159 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001160 }
1161 }
Mike Stump1eb44332009-09-09 15:08:12 +00001162 if (const ObjCObjectPointerType *FromPtrType =
Steve Naroff14108da2009-07-10 23:34:53 +00001163 FromType->getAsObjCObjectPointerType())
Mike Stump1eb44332009-09-09 15:08:12 +00001164 if (const ObjCObjectPointerType *ToPtrType =
Steve Naroff14108da2009-07-10 23:34:53 +00001165 ToType->getAsObjCObjectPointerType()) {
1166 // Objective-C++ conversions are always okay.
1167 // FIXME: We should have a different class of conversions for the
1168 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001169 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001170 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001171
Steve Naroff14108da2009-07-10 23:34:53 +00001172 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001173 return false;
1174}
1175
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001176/// IsMemberPointerConversion - Determines whether the conversion of the
1177/// expression From, which has the (possibly adjusted) type FromType, can be
1178/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1179/// If so, returns true and places the converted type (that might differ from
1180/// ToType in its cv-qualifiers at some level) into ConvertedType.
1181bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Mike Stump1eb44332009-09-09 15:08:12 +00001182 QualType ToType, QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001183 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001184 if (!ToTypePtr)
1185 return false;
1186
1187 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1188 if (From->isNullPointerConstant(Context)) {
1189 ConvertedType = ToType;
1190 return true;
1191 }
1192
1193 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001194 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001195 if (!FromTypePtr)
1196 return false;
1197
1198 // A pointer to member of B can be converted to a pointer to member of D,
1199 // where D is derived from B (C++ 4.11p2).
1200 QualType FromClass(FromTypePtr->getClass(), 0);
1201 QualType ToClass(ToTypePtr->getClass(), 0);
1202 // FIXME: What happens when these are dependent? Is this function even called?
1203
1204 if (IsDerivedFrom(ToClass, FromClass)) {
1205 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1206 ToClass.getTypePtr());
1207 return true;
1208 }
1209
1210 return false;
1211}
1212
1213/// CheckMemberPointerConversion - Check the member pointer conversion from the
1214/// expression From to the type ToType. This routine checks for ambiguous or
1215/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1216/// for which IsMemberPointerConversion has already returned true. It returns
1217/// true and produces a diagnostic if there was an error, or returns false
1218/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001219bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001220 CastExpr::CastKind &Kind) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001221 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001222 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001223 if (!FromPtrType) {
1224 // This must be a null pointer to member pointer conversion
Mike Stump1eb44332009-09-09 15:08:12 +00001225 assert(From->isNullPointerConstant(Context) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001226 "Expr must be null pointer constant!");
1227 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001228 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001229 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001230
Ted Kremenek6217b802009-07-29 21:53:49 +00001231 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001232 assert(ToPtrType && "No member pointer cast has a target type "
1233 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001234
Sebastian Redl21593ac2009-01-28 18:33:18 +00001235 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1236 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001237
Sebastian Redl21593ac2009-01-28 18:33:18 +00001238 // FIXME: What about dependent types?
1239 assert(FromClass->isRecordType() && "Pointer into non-class.");
1240 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001241
Sebastian Redl21593ac2009-01-28 18:33:18 +00001242 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1243 /*DetectVirtual=*/true);
1244 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1245 assert(DerivationOkay &&
1246 "Should not have been called if derivation isn't OK.");
1247 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001248
Sebastian Redl21593ac2009-01-28 18:33:18 +00001249 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1250 getUnqualifiedType())) {
1251 // Derivation is ambiguous. Redo the check to find the exact paths.
1252 Paths.clear();
1253 Paths.setRecordingPaths(true);
1254 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1255 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1256 (void)StillOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001257
Sebastian Redl21593ac2009-01-28 18:33:18 +00001258 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1259 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1260 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1261 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001262 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001263
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001264 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001265 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1266 << FromClass << ToClass << QualType(VBase, 0)
1267 << From->getSourceRange();
1268 return true;
1269 }
1270
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001271 // Must be a base to derived member conversion.
1272 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001273 return false;
1274}
1275
Douglas Gregor98cd5992008-10-21 23:43:52 +00001276/// IsQualificationConversion - Determines whether the conversion from
1277/// an rvalue of type FromType to ToType is a qualification conversion
1278/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001279bool
1280Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001281 FromType = Context.getCanonicalType(FromType);
1282 ToType = Context.getCanonicalType(ToType);
1283
1284 // If FromType and ToType are the same type, this is not a
1285 // qualification conversion.
1286 if (FromType == ToType)
1287 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001288
Douglas Gregor98cd5992008-10-21 23:43:52 +00001289 // (C++ 4.4p4):
1290 // A conversion can add cv-qualifiers at levels other than the first
1291 // in multi-level pointers, subject to the following rules: [...]
1292 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001293 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001294 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001295 // Within each iteration of the loop, we check the qualifiers to
1296 // determine if this still looks like a qualification
1297 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001298 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001299 // until there are no more pointers or pointers-to-members left to
1300 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001301 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001302
1303 // -- for every j > 0, if const is in cv 1,j then const is in cv
1304 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001305 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001306 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001307
Douglas Gregor98cd5992008-10-21 23:43:52 +00001308 // -- if the cv 1,j and cv 2,j are different, then const is in
1309 // every cv for 0 < k < j.
1310 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001311 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001312 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001313
Douglas Gregor98cd5992008-10-21 23:43:52 +00001314 // Keep track of whether all prior cv-qualifiers in the "to" type
1315 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001316 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001317 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001318 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001319
1320 // We are left with FromType and ToType being the pointee types
1321 // after unwrapping the original FromType and ToType the same number
1322 // of types. If we unwrapped any pointers, and if FromType and
1323 // ToType have the same unqualified type (since we checked
1324 // qualifiers above), then this is a qualification conversion.
1325 return UnwrappedAnyPointer &&
1326 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1327}
1328
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001329/// \brief Given a function template or function, extract the function template
1330/// declaration (if any) and the underlying function declaration.
1331template<typename T>
1332static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1333 FunctionTemplateDecl *&FunctionTemplate) {
1334 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1335 if (FunctionTemplate)
1336 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1337 else
1338 Function = cast<T>(Orig);
1339}
1340
Douglas Gregor734d9862009-01-30 23:27:23 +00001341/// Determines whether there is a user-defined conversion sequence
1342/// (C++ [over.ics.user]) that converts expression From to the type
1343/// ToType. If such a conversion exists, User will contain the
1344/// user-defined conversion sequence that performs such a conversion
1345/// and this routine will return true. Otherwise, this routine returns
1346/// false and User is unspecified.
1347///
1348/// \param AllowConversionFunctions true if the conversion should
1349/// consider conversion functions at all. If false, only constructors
1350/// will be considered.
1351///
1352/// \param AllowExplicit true if the conversion should consider C++0x
1353/// "explicit" conversion functions as well as non-explicit conversion
1354/// functions (C++0x [class.conv.fct]p2).
Sebastian Redle2b68332009-04-12 17:16:29 +00001355///
1356/// \param ForceRValue true if the expression should be treated as an rvalue
1357/// for overload resolution.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001358Sema::OverloadingResult Sema::IsUserDefinedConversion(
1359 Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001360 UserDefinedConversionSequence& User,
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +00001361 OverloadCandidateSet& CandidateSet,
Douglas Gregor734d9862009-01-30 23:27:23 +00001362 bool AllowConversionFunctions,
Mike Stump1eb44332009-09-09 15:08:12 +00001363 bool AllowExplicit, bool ForceRValue) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001364 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001365 if (CXXRecordDecl *ToRecordDecl
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001366 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1367 // C++ [over.match.ctor]p1:
1368 // When objects of class type are direct-initialized (8.5), or
1369 // copy-initialized from an expression of the same or a
1370 // derived class type (8.5), overload resolution selects the
1371 // constructor. [...] For copy-initialization, the candidate
1372 // functions are all the converting constructors (12.3.1) of
1373 // that class. The argument list is the expression-list within
1374 // the parentheses of the initializer.
Mike Stump1eb44332009-09-09 15:08:12 +00001375 DeclarationName ConstructorName
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001376 = Context.DeclarationNames.getCXXConstructorName(
1377 Context.getCanonicalType(ToType).getUnqualifiedType());
1378 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump1eb44332009-09-09 15:08:12 +00001379 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001380 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001381 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00001382 // Find the constructor (which may be a template).
1383 CXXConstructorDecl *Constructor = 0;
1384 FunctionTemplateDecl *ConstructorTmpl
1385 = dyn_cast<FunctionTemplateDecl>(*Con);
1386 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001387 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001388 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1389 else
1390 Constructor = cast<CXXConstructorDecl>(*Con);
Mike Stump1eb44332009-09-09 15:08:12 +00001391
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001392 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001393 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001394 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001395 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
Douglas Gregordec06662009-08-21 18:42:58 +00001396 1, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00001397 /*SuppressUserConversions=*/true,
Douglas Gregordec06662009-08-21 18:42:58 +00001398 ForceRValue);
1399 else
1400 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1401 /*SuppressUserConversions=*/true, ForceRValue);
1402 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001403 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001404 }
1405 }
1406
Douglas Gregor734d9862009-01-30 23:27:23 +00001407 if (!AllowConversionFunctions) {
1408 // Don't allow any conversion functions to enter the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00001409 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1410 PDiag(0)
Anders Carlssonb7906612009-08-26 23:45:07 +00001411 << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001412 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001413 } else if (const RecordType *FromRecordType
Ted Kremenek6217b802009-07-29 21:53:49 +00001414 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001415 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001416 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1417 // Add all of the conversion functions as candidates.
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001418 OverloadedFunctionDecl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001419 = FromRecordDecl->getVisibleConversionFunctions();
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001420 for (OverloadedFunctionDecl::function_iterator Func
1421 = Conversions->function_begin();
1422 Func != Conversions->function_end(); ++Func) {
1423 CXXConversionDecl *Conv;
1424 FunctionTemplateDecl *ConvTemplate;
1425 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1426 if (ConvTemplate)
1427 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1428 else
1429 Conv = dyn_cast<CXXConversionDecl>(*Func);
1430
1431 if (AllowExplicit || !Conv->isExplicit()) {
1432 if (ConvTemplate)
1433 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1434 CandidateSet);
1435 else
1436 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1437 }
1438 }
1439 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001440 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001441
1442 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001443 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001444 case OR_Success:
1445 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001446 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001447 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1448 // C++ [over.ics.user]p1:
1449 // If the user-defined conversion is specified by a
1450 // constructor (12.3.1), the initial standard conversion
1451 // sequence converts the source type to the type required by
1452 // the argument of the constructor.
1453 //
1454 // FIXME: What about ellipsis conversions?
1455 QualType ThisType = Constructor->getThisType(Context);
1456 User.Before = Best->Conversions[0].Standard;
1457 User.ConversionFunction = Constructor;
1458 User.After.setAsIdentityConversion();
Mike Stump1eb44332009-09-09 15:08:12 +00001459 User.After.FromTypePtr
Ted Kremenek6217b802009-07-29 21:53:49 +00001460 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor60d62c22008-10-31 16:23:19 +00001461 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001462 return OR_Success;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001463 } else if (CXXConversionDecl *Conversion
1464 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1465 // C++ [over.ics.user]p1:
1466 //
1467 // [...] If the user-defined conversion is specified by a
1468 // conversion function (12.3.2), the initial standard
1469 // conversion sequence converts the source type to the
1470 // implicit object parameter of the conversion function.
1471 User.Before = Best->Conversions[0].Standard;
1472 User.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00001473
1474 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001475 // The second standard conversion sequence converts the
1476 // result of the user-defined conversion to the target type
1477 // for the sequence. Since an implicit conversion sequence
1478 // is an initialization, the special rules for
1479 // initialization by user-defined conversion apply when
1480 // selecting the best user-defined conversion for a
1481 // user-defined conversion sequence (see 13.3.3 and
1482 // 13.3.3.1).
1483 User.After = Best->FinalConversion;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001484 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001485 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001486 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001487 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001488 }
Mike Stump1eb44332009-09-09 15:08:12 +00001489
Douglas Gregor60d62c22008-10-31 16:23:19 +00001490 case OR_No_Viable_Function:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001491 return OR_No_Viable_Function;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001492 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001493 // No conversion here! We're done.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001494 return OR_Deleted;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001495
1496 case OR_Ambiguous:
1497 // FIXME: See C++ [over.best.ics]p10 for the handling of
1498 // ambiguous conversion sequences.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001499 return OR_Ambiguous;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001500 }
1501
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001502 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001503}
1504
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001505/// CompareImplicitConversionSequences - Compare two implicit
1506/// conversion sequences to determine whether one is better than the
1507/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00001508ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001509Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1510 const ImplicitConversionSequence& ICS2)
1511{
1512 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1513 // conversion sequences (as defined in 13.3.3.1)
1514 // -- a standard conversion sequence (13.3.3.1.1) is a better
1515 // conversion sequence than a user-defined conversion sequence or
1516 // an ellipsis conversion sequence, and
1517 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1518 // conversion sequence than an ellipsis conversion sequence
1519 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00001520 //
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001521 if (ICS1.ConversionKind < ICS2.ConversionKind)
1522 return ImplicitConversionSequence::Better;
1523 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1524 return ImplicitConversionSequence::Worse;
1525
1526 // Two implicit conversion sequences of the same form are
1527 // indistinguishable conversion sequences unless one of the
1528 // following rules apply: (C++ 13.3.3.2p3):
1529 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1530 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump1eb44332009-09-09 15:08:12 +00001531 else if (ICS1.ConversionKind ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001532 ImplicitConversionSequence::UserDefinedConversion) {
1533 // User-defined conversion sequence U1 is a better conversion
1534 // sequence than another user-defined conversion sequence U2 if
1535 // they contain the same user-defined conversion function or
1536 // constructor and if the second standard conversion sequence of
1537 // U1 is better than the second standard conversion sequence of
1538 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001539 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001540 ICS2.UserDefined.ConversionFunction)
1541 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1542 ICS2.UserDefined.After);
1543 }
1544
1545 return ImplicitConversionSequence::Indistinguishable;
1546}
1547
1548/// CompareStandardConversionSequences - Compare two standard
1549/// conversion sequences to determine whether one is better than the
1550/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001551ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001552Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1553 const StandardConversionSequence& SCS2)
1554{
1555 // Standard conversion sequence S1 is a better conversion sequence
1556 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1557
1558 // -- S1 is a proper subsequence of S2 (comparing the conversion
1559 // sequences in the canonical form defined by 13.3.3.1.1,
1560 // excluding any Lvalue Transformation; the identity conversion
1561 // sequence is considered to be a subsequence of any
1562 // non-identity conversion sequence) or, if not that,
1563 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1564 // Neither is a proper subsequence of the other. Do nothing.
1565 ;
1566 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1567 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001568 (SCS1.Second == ICK_Identity &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001569 SCS1.Third == ICK_Identity))
1570 // SCS1 is a proper subsequence of SCS2.
1571 return ImplicitConversionSequence::Better;
1572 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1573 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001574 (SCS2.Second == ICK_Identity &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001575 SCS2.Third == ICK_Identity))
1576 // SCS2 is a proper subsequence of SCS1.
1577 return ImplicitConversionSequence::Worse;
1578
1579 // -- the rank of S1 is better than the rank of S2 (by the rules
1580 // defined below), or, if not that,
1581 ImplicitConversionRank Rank1 = SCS1.getRank();
1582 ImplicitConversionRank Rank2 = SCS2.getRank();
1583 if (Rank1 < Rank2)
1584 return ImplicitConversionSequence::Better;
1585 else if (Rank2 < Rank1)
1586 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001587
Douglas Gregor57373262008-10-22 14:17:15 +00001588 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1589 // are indistinguishable unless one of the following rules
1590 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00001591
Douglas Gregor57373262008-10-22 14:17:15 +00001592 // A conversion that is not a conversion of a pointer, or
1593 // pointer to member, to bool is better than another conversion
1594 // that is such a conversion.
1595 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1596 return SCS2.isPointerConversionToBool()
1597 ? ImplicitConversionSequence::Better
1598 : ImplicitConversionSequence::Worse;
1599
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001600 // C++ [over.ics.rank]p4b2:
1601 //
1602 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001603 // conversion of B* to A* is better than conversion of B* to
1604 // void*, and conversion of A* to void* is better than conversion
1605 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00001606 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001607 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001608 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001609 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001610 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1611 // Exactly one of the conversion sequences is a conversion to
1612 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001613 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1614 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001615 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1616 // Neither conversion sequence converts to a void pointer; compare
1617 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001618 if (ImplicitConversionSequence::CompareKind DerivedCK
1619 = CompareDerivedToBaseConversions(SCS1, SCS2))
1620 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001621 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1622 // Both conversion sequences are conversions to void
1623 // pointers. Compare the source types to determine if there's an
1624 // inheritance relationship in their sources.
1625 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1626 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1627
1628 // Adjust the types we're converting from via the array-to-pointer
1629 // conversion, if we need to.
1630 if (SCS1.First == ICK_Array_To_Pointer)
1631 FromType1 = Context.getArrayDecayedType(FromType1);
1632 if (SCS2.First == ICK_Array_To_Pointer)
1633 FromType2 = Context.getArrayDecayedType(FromType2);
1634
Mike Stump1eb44332009-09-09 15:08:12 +00001635 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001636 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001637 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001638 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001639
1640 if (IsDerivedFrom(FromPointee2, FromPointee1))
1641 return ImplicitConversionSequence::Better;
1642 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1643 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001644
1645 // Objective-C++: If one interface is more specific than the
1646 // other, it is the better one.
1647 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1648 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1649 if (FromIface1 && FromIface1) {
1650 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1651 return ImplicitConversionSequence::Better;
1652 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1653 return ImplicitConversionSequence::Worse;
1654 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001655 }
Douglas Gregor57373262008-10-22 14:17:15 +00001656
1657 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1658 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00001659 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001660 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001661 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001662
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001663 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001664 // C++0x [over.ics.rank]p3b4:
1665 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1666 // implicit object parameter of a non-static member function declared
1667 // without a ref-qualifier, and S1 binds an rvalue reference to an
1668 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00001669 // FIXME: We don't know if we're dealing with the implicit object parameter,
1670 // or if the member function in this case has a ref qualifier.
1671 // (Of course, we don't have ref qualifiers yet.)
1672 if (SCS1.RRefBinding != SCS2.RRefBinding)
1673 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1674 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001675
1676 // C++ [over.ics.rank]p3b4:
1677 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1678 // which the references refer are the same type except for
1679 // top-level cv-qualifiers, and the type to which the reference
1680 // initialized by S2 refers is more cv-qualified than the type
1681 // to which the reference initialized by S1 refers.
Sebastian Redla9845802009-03-29 15:27:50 +00001682 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1683 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001684 T1 = Context.getCanonicalType(T1);
1685 T2 = Context.getCanonicalType(T2);
1686 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1687 if (T2.isMoreQualifiedThan(T1))
1688 return ImplicitConversionSequence::Better;
1689 else if (T1.isMoreQualifiedThan(T2))
1690 return ImplicitConversionSequence::Worse;
1691 }
1692 }
Douglas Gregor57373262008-10-22 14:17:15 +00001693
1694 return ImplicitConversionSequence::Indistinguishable;
1695}
1696
1697/// CompareQualificationConversions - Compares two standard conversion
1698/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00001699/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1700ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00001701Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00001702 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00001703 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001704 // -- S1 and S2 differ only in their qualification conversion and
1705 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1706 // cv-qualification signature of type T1 is a proper subset of
1707 // the cv-qualification signature of type T2, and S1 is not the
1708 // deprecated string literal array-to-pointer conversion (4.2).
1709 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1710 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1711 return ImplicitConversionSequence::Indistinguishable;
1712
1713 // FIXME: the example in the standard doesn't use a qualification
1714 // conversion (!)
1715 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1716 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1717 T1 = Context.getCanonicalType(T1);
1718 T2 = Context.getCanonicalType(T2);
1719
1720 // If the types are the same, we won't learn anything by unwrapped
1721 // them.
1722 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1723 return ImplicitConversionSequence::Indistinguishable;
1724
Mike Stump1eb44332009-09-09 15:08:12 +00001725 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00001726 = ImplicitConversionSequence::Indistinguishable;
1727 while (UnwrapSimilarPointerTypes(T1, T2)) {
1728 // Within each iteration of the loop, we check the qualifiers to
1729 // determine if this still looks like a qualification
1730 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001731 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001732 // until there are no more pointers or pointers-to-members left
1733 // to unwrap. This essentially mimics what
1734 // IsQualificationConversion does, but here we're checking for a
1735 // strict subset of qualifiers.
1736 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1737 // The qualifiers are the same, so this doesn't tell us anything
1738 // about how the sequences rank.
1739 ;
1740 else if (T2.isMoreQualifiedThan(T1)) {
1741 // T1 has fewer qualifiers, so it could be the better sequence.
1742 if (Result == ImplicitConversionSequence::Worse)
1743 // Neither has qualifiers that are a subset of the other's
1744 // qualifiers.
1745 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001746
Douglas Gregor57373262008-10-22 14:17:15 +00001747 Result = ImplicitConversionSequence::Better;
1748 } else if (T1.isMoreQualifiedThan(T2)) {
1749 // T2 has fewer qualifiers, so it could be the better sequence.
1750 if (Result == ImplicitConversionSequence::Better)
1751 // Neither has qualifiers that are a subset of the other's
1752 // qualifiers.
1753 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001754
Douglas Gregor57373262008-10-22 14:17:15 +00001755 Result = ImplicitConversionSequence::Worse;
1756 } else {
1757 // Qualifiers are disjoint.
1758 return ImplicitConversionSequence::Indistinguishable;
1759 }
1760
1761 // If the types after this point are equivalent, we're done.
1762 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1763 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001764 }
1765
Douglas Gregor57373262008-10-22 14:17:15 +00001766 // Check that the winning standard conversion sequence isn't using
1767 // the deprecated string literal array to pointer conversion.
1768 switch (Result) {
1769 case ImplicitConversionSequence::Better:
1770 if (SCS1.Deprecated)
1771 Result = ImplicitConversionSequence::Indistinguishable;
1772 break;
1773
1774 case ImplicitConversionSequence::Indistinguishable:
1775 break;
1776
1777 case ImplicitConversionSequence::Worse:
1778 if (SCS2.Deprecated)
1779 Result = ImplicitConversionSequence::Indistinguishable;
1780 break;
1781 }
1782
1783 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001784}
1785
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001786/// CompareDerivedToBaseConversions - Compares two standard conversion
1787/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001788/// various kinds of derived-to-base conversions (C++
1789/// [over.ics.rank]p4b3). As part of these checks, we also look at
1790/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001791ImplicitConversionSequence::CompareKind
1792Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1793 const StandardConversionSequence& SCS2) {
1794 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1795 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1796 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1797 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1798
1799 // Adjust the types we're converting from via the array-to-pointer
1800 // conversion, if we need to.
1801 if (SCS1.First == ICK_Array_To_Pointer)
1802 FromType1 = Context.getArrayDecayedType(FromType1);
1803 if (SCS2.First == ICK_Array_To_Pointer)
1804 FromType2 = Context.getArrayDecayedType(FromType2);
1805
1806 // Canonicalize all of the types.
1807 FromType1 = Context.getCanonicalType(FromType1);
1808 ToType1 = Context.getCanonicalType(ToType1);
1809 FromType2 = Context.getCanonicalType(FromType2);
1810 ToType2 = Context.getCanonicalType(ToType2);
1811
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001812 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001813 //
1814 // If class B is derived directly or indirectly from class A and
1815 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001816 //
1817 // For Objective-C, we let A, B, and C also be Objective-C
1818 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001819
1820 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00001821 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001822 SCS2.Second == ICK_Pointer_Conversion &&
1823 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1824 FromType1->isPointerType() && FromType2->isPointerType() &&
1825 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001826 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001827 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00001828 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001829 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001830 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001831 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001832 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001833 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001834
1835 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1836 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1837 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1838 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1839
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001840 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001841 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1842 if (IsDerivedFrom(ToPointee1, ToPointee2))
1843 return ImplicitConversionSequence::Better;
1844 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1845 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001846
1847 if (ToIface1 && ToIface2) {
1848 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1849 return ImplicitConversionSequence::Better;
1850 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1851 return ImplicitConversionSequence::Worse;
1852 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001853 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001854
1855 // -- conversion of B* to A* is better than conversion of C* to A*,
1856 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1857 if (IsDerivedFrom(FromPointee2, FromPointee1))
1858 return ImplicitConversionSequence::Better;
1859 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1860 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Douglas Gregorcb7de522008-11-26 23:31:11 +00001862 if (FromIface1 && FromIface2) {
1863 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1864 return ImplicitConversionSequence::Better;
1865 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1866 return ImplicitConversionSequence::Worse;
1867 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001868 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001869 }
1870
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001871 // Compare based on reference bindings.
1872 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1873 SCS1.Second == ICK_Derived_To_Base) {
1874 // -- binding of an expression of type C to a reference of type
1875 // B& is better than binding an expression of type C to a
1876 // reference of type A&,
1877 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1878 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1879 if (IsDerivedFrom(ToType1, ToType2))
1880 return ImplicitConversionSequence::Better;
1881 else if (IsDerivedFrom(ToType2, ToType1))
1882 return ImplicitConversionSequence::Worse;
1883 }
1884
Douglas Gregor225c41e2008-11-03 19:09:14 +00001885 // -- binding of an expression of type B to a reference of type
1886 // A& is better than binding an expression of type C to a
1887 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001888 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1889 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1890 if (IsDerivedFrom(FromType2, FromType1))
1891 return ImplicitConversionSequence::Better;
1892 else if (IsDerivedFrom(FromType1, FromType2))
1893 return ImplicitConversionSequence::Worse;
1894 }
1895 }
1896
1897
1898 // FIXME: conversion of A::* to B::* is better than conversion of
1899 // A::* to C::*,
1900
1901 // FIXME: conversion of B::* to C::* is better than conversion of
1902 // A::* to C::*, and
1903
Douglas Gregor225c41e2008-11-03 19:09:14 +00001904 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1905 SCS1.Second == ICK_Derived_To_Base) {
1906 // -- conversion of C to B is better than conversion of C to A,
1907 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1908 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1909 if (IsDerivedFrom(ToType1, ToType2))
1910 return ImplicitConversionSequence::Better;
1911 else if (IsDerivedFrom(ToType2, ToType1))
1912 return ImplicitConversionSequence::Worse;
1913 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001914
Douglas Gregor225c41e2008-11-03 19:09:14 +00001915 // -- conversion of B to A is better than conversion of C to A.
1916 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1917 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1918 if (IsDerivedFrom(FromType2, FromType1))
1919 return ImplicitConversionSequence::Better;
1920 else if (IsDerivedFrom(FromType1, FromType2))
1921 return ImplicitConversionSequence::Worse;
1922 }
1923 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001924
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001925 return ImplicitConversionSequence::Indistinguishable;
1926}
1927
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001928/// TryCopyInitialization - Try to copy-initialize a value of type
1929/// ToType from the expression From. Return the implicit conversion
1930/// sequence required to pass this argument, which may be a bad
1931/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00001932/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redle2b68332009-04-12 17:16:29 +00001933/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1934/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00001935ImplicitConversionSequence
1936Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001937 bool SuppressUserConversions, bool ForceRValue,
1938 bool InOverloadResolution) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00001939 if (ToType->isReferenceType()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001940 ImplicitConversionSequence ICS;
Mike Stump1eb44332009-09-09 15:08:12 +00001941 CheckReferenceInit(From, ToType,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001942 SuppressUserConversions,
1943 /*AllowExplicit=*/false,
1944 ForceRValue,
1945 &ICS);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001946 return ICS;
1947 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001948 return TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001949 SuppressUserConversions,
1950 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001951 ForceRValue,
1952 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001953 }
1954}
1955
Sebastian Redle2b68332009-04-12 17:16:29 +00001956/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1957/// the expression @p From. Returns true (and emits a diagnostic) if there was
1958/// an error, returns false if the initialization succeeded. Elidable should
1959/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1960/// differently in C++0x for this case.
Mike Stump1eb44332009-09-09 15:08:12 +00001961bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +00001962 const char* Flavor, bool Elidable) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001963 if (!getLangOptions().CPlusPlus) {
1964 // In C, argument passing is the same as performing an assignment.
1965 QualType FromType = From->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001966
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001967 AssignConvertType ConvTy =
1968 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00001969 if (ConvTy != Compatible &&
1970 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1971 ConvTy = Compatible;
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001973 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1974 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001975 }
Sebastian Redle2b68332009-04-12 17:16:29 +00001976
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001977 if (ToType->isReferenceType())
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001978 return CheckReferenceInit(From, ToType,
1979 /*SuppressUserConversions=*/false,
1980 /*AllowExplicit=*/false,
1981 /*ForceRValue=*/false);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001982
Sebastian Redle2b68332009-04-12 17:16:29 +00001983 if (!PerformImplicitConversion(From, ToType, Flavor,
1984 /*AllowExplicit=*/false, Elidable))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001985 return false;
Sebastian Redle2b68332009-04-12 17:16:29 +00001986
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001987 return Diag(From->getSourceRange().getBegin(),
1988 diag::err_typecheck_convert_incompatible)
1989 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001990}
1991
Douglas Gregor96176b32008-11-18 23:14:02 +00001992/// TryObjectArgumentInitialization - Try to initialize the object
1993/// parameter of the given member function (@c Method) from the
1994/// expression @p From.
1995ImplicitConversionSequence
1996Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1997 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1998 unsigned MethodQuals = Method->getTypeQualifiers();
1999 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
2000
2001 // Set up the conversion sequence as a "bad" conversion, to allow us
2002 // to exit early.
2003 ImplicitConversionSequence ICS;
2004 ICS.Standard.setAsIdentityConversion();
2005 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2006
2007 // We need to have an object of class type.
2008 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002009 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00002010 FromType = PT->getPointeeType();
2011
2012 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002013
2014 // The implicit object parmeter is has the type "reference to cv X",
2015 // where X is the class of which the function is a member
2016 // (C++ [over.match.funcs]p4). However, when finding an implicit
2017 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00002018 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00002019 // (C++ [over.match.funcs]p5). We perform a simplified version of
2020 // reference binding here, that allows class rvalues to bind to
2021 // non-constant references.
2022
2023 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2024 // with the implicit object parameter (C++ [over.match.funcs]p5).
2025 QualType FromTypeCanon = Context.getCanonicalType(FromType);
2026 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2027 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2028 return ICS;
2029
2030 // Check that we have either the same type or a derived type. It
2031 // affects the conversion rank.
2032 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2033 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2034 ICS.Standard.Second = ICK_Identity;
2035 else if (IsDerivedFrom(FromType, ClassType))
2036 ICS.Standard.Second = ICK_Derived_To_Base;
2037 else
2038 return ICS;
2039
2040 // Success. Mark this as a reference binding.
2041 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2042 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2043 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2044 ICS.Standard.ReferenceBinding = true;
2045 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00002046 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002047 return ICS;
2048}
2049
2050/// PerformObjectArgumentInitialization - Perform initialization of
2051/// the implicit object parameter for the given Method with the given
2052/// expression.
2053bool
2054Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002055 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00002056 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00002057 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Ted Kremenek6217b802009-07-29 21:53:49 +00002059 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002060 FromRecordType = PT->getPointeeType();
2061 DestType = Method->getThisType(Context);
2062 } else {
2063 FromRecordType = From->getType();
2064 DestType = ImplicitParamRecordType;
2065 }
2066
Mike Stump1eb44332009-09-09 15:08:12 +00002067 ImplicitConversionSequence ICS
Douglas Gregor96176b32008-11-18 23:14:02 +00002068 = TryObjectArgumentInitialization(From, Method);
2069 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2070 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002071 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00002072 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002073
Douglas Gregor96176b32008-11-18 23:14:02 +00002074 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssona552f7c2009-05-01 18:34:30 +00002075 CheckDerivedToBaseConversion(FromRecordType,
2076 ImplicitParamRecordType,
Douglas Gregor96176b32008-11-18 23:14:02 +00002077 From->getSourceRange().getBegin(),
2078 From->getSourceRange()))
2079 return true;
2080
Mike Stump1eb44332009-09-09 15:08:12 +00002081 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson116b7d92009-08-07 18:45:49 +00002082 /*isLvalue=*/true);
Douglas Gregor96176b32008-11-18 23:14:02 +00002083 return false;
2084}
2085
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002086/// TryContextuallyConvertToBool - Attempt to contextually convert the
2087/// expression From to bool (C++0x [conv]p3).
2088ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump1eb44332009-09-09 15:08:12 +00002089 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002090 // FIXME: Are these flags correct?
2091 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00002092 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00002093 /*ForceRValue=*/false,
2094 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002095}
2096
2097/// PerformContextuallyConvertToBool - Perform a contextual conversion
2098/// of the expression From to bool (C++0x [conv]p3).
2099bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2100 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2101 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2102 return false;
2103
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +00002104 OverloadCandidateSet CandidateSet;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002105 if (IsUserDefinedConversion(From, Context.BoolTy, ICS.UserDefined,
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +00002106 CandidateSet,
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002107 true, true, false) != OR_Ambiguous)
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +00002108 return Diag(From->getSourceRange().getBegin(),
2109 diag::err_typecheck_bool_condition)
2110 << From->getType() << From->getSourceRange();
2111 Diag(From->getSourceRange().getBegin(),
2112 diag::err_typecheck_ambiguous_bool_condition)
2113 << From->getType() << From->getSourceRange();
2114 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
2115 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002116}
2117
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002118/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00002119/// candidate functions, using the given function call arguments. If
2120/// @p SuppressUserConversions, then don't allow user-defined
2121/// conversions via constructors or conversion operators.
Sebastian Redle2b68332009-04-12 17:16:29 +00002122/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2123/// hacky way to implement the overloading rules for elidable copy
2124/// initialization in C++0x (C++0x 12.8p15).
Mike Stump1eb44332009-09-09 15:08:12 +00002125void
2126Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002127 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002128 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00002129 bool SuppressUserConversions,
Mike Stump1eb44332009-09-09 15:08:12 +00002130 bool ForceRValue) {
2131 const FunctionProtoType* Proto
Douglas Gregor72564e72009-02-26 23:50:07 +00002132 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002133 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00002134 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002135 "Use AddConversionCandidate for conversion functions");
Mike Stump1eb44332009-09-09 15:08:12 +00002136 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00002137 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00002138
Douglas Gregor88a35142008-12-22 05:46:06 +00002139 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002140 if (!isa<CXXConstructorDecl>(Method)) {
2141 // If we get here, it's because we're calling a member function
2142 // that is named without a member access expression (e.g.,
2143 // "this->f") that was either written explicitly or created
2144 // implicitly. This can happen with a qualified call to a member
2145 // function, e.g., X::f(). We use a NULL object as the implied
2146 // object argument (C++ [over.call.func]p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002147 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002148 SuppressUserConversions, ForceRValue);
2149 return;
2150 }
2151 // We treat a constructor like a non-member function, since its object
2152 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00002153 }
2154
2155
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002156 // Add this candidate
2157 CandidateSet.push_back(OverloadCandidate());
2158 OverloadCandidate& Candidate = CandidateSet.back();
2159 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00002160 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002161 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002162 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002163
2164 unsigned NumArgsInProto = Proto->getNumArgs();
2165
2166 // (C++ 13.3.2p2): A candidate function having fewer than m
2167 // parameters is viable only if it has an ellipsis in its parameter
2168 // list (8.3.5).
2169 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2170 Candidate.Viable = false;
2171 return;
2172 }
2173
2174 // (C++ 13.3.2p2): A candidate function having more than m parameters
2175 // is viable only if the (m+1)st parameter has a default argument
2176 // (8.3.6). For the purposes of overload resolution, the
2177 // parameter list is truncated on the right, so that there are
2178 // exactly m parameters.
2179 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2180 if (NumArgs < MinRequiredArgs) {
2181 // Not enough arguments.
2182 Candidate.Viable = false;
2183 return;
2184 }
2185
2186 // Determine the implicit conversion sequences for each of the
2187 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002188 Candidate.Conversions.resize(NumArgs);
2189 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2190 if (ArgIdx < NumArgsInProto) {
2191 // (C++ 13.3.2p3): for F to be a viable function, there shall
2192 // exist for each argument an implicit conversion sequence
2193 // (13.3.3.1) that converts that argument to the corresponding
2194 // parameter of F.
2195 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002196 Candidate.Conversions[ArgIdx]
2197 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002198 SuppressUserConversions, ForceRValue,
2199 /*InOverloadResolution=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00002200 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002201 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002202 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002203 break;
2204 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002205 } else {
2206 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2207 // argument for which there is no corresponding parameter is
2208 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002209 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002210 = ImplicitConversionSequence::EllipsisConversion;
2211 }
2212 }
2213}
2214
Douglas Gregor063daf62009-03-13 18:40:31 +00002215/// \brief Add all of the function declarations in the given function set to
2216/// the overload canddiate set.
2217void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2218 Expr **Args, unsigned NumArgs,
2219 OverloadCandidateSet& CandidateSet,
2220 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00002221 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor063daf62009-03-13 18:40:31 +00002222 FEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00002223 F != FEnd; ++F) {
2224 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
Mike Stump1eb44332009-09-09 15:08:12 +00002225 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00002226 SuppressUserConversions);
2227 else
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002228 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2229 /*FIXME: explicit args */false, 0, 0,
Mike Stump1eb44332009-09-09 15:08:12 +00002230 Args, NumArgs, CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00002231 SuppressUserConversions);
2232 }
Douglas Gregor063daf62009-03-13 18:40:31 +00002233}
2234
Douglas Gregor96176b32008-11-18 23:14:02 +00002235/// AddMethodCandidate - Adds the given C++ member function to the set
2236/// of candidate functions, using the given function call arguments
2237/// and the object argument (@c Object). For example, in a call
2238/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2239/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2240/// allow user-defined conversions via constructors or conversion
Sebastian Redle2b68332009-04-12 17:16:29 +00002241/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2242/// a slightly hacky way to implement the overloading rules for elidable copy
2243/// initialization in C++0x (C++0x 12.8p15).
Mike Stump1eb44332009-09-09 15:08:12 +00002244void
Douglas Gregor96176b32008-11-18 23:14:02 +00002245Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2246 Expr **Args, unsigned NumArgs,
2247 OverloadCandidateSet& CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00002248 bool SuppressUserConversions, bool ForceRValue) {
2249 const FunctionProtoType* Proto
Douglas Gregor72564e72009-02-26 23:50:07 +00002250 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002251 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002252 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor96176b32008-11-18 23:14:02 +00002253 "Use AddConversionCandidate for conversion functions");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002254 assert(!isa<CXXConstructorDecl>(Method) &&
2255 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00002256
2257 // Add this candidate
2258 CandidateSet.push_back(OverloadCandidate());
2259 OverloadCandidate& Candidate = CandidateSet.back();
2260 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002261 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002262 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002263
2264 unsigned NumArgsInProto = Proto->getNumArgs();
2265
2266 // (C++ 13.3.2p2): A candidate function having fewer than m
2267 // parameters is viable only if it has an ellipsis in its parameter
2268 // list (8.3.5).
2269 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2270 Candidate.Viable = false;
2271 return;
2272 }
2273
2274 // (C++ 13.3.2p2): A candidate function having more than m parameters
2275 // is viable only if the (m+1)st parameter has a default argument
2276 // (8.3.6). For the purposes of overload resolution, the
2277 // parameter list is truncated on the right, so that there are
2278 // exactly m parameters.
2279 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2280 if (NumArgs < MinRequiredArgs) {
2281 // Not enough arguments.
2282 Candidate.Viable = false;
2283 return;
2284 }
2285
2286 Candidate.Viable = true;
2287 Candidate.Conversions.resize(NumArgs + 1);
2288
Douglas Gregor88a35142008-12-22 05:46:06 +00002289 if (Method->isStatic() || !Object)
2290 // The implicit object argument is ignored.
2291 Candidate.IgnoreObjectArgument = true;
2292 else {
2293 // Determine the implicit conversion sequence for the object
2294 // parameter.
2295 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
Mike Stump1eb44332009-09-09 15:08:12 +00002296 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor88a35142008-12-22 05:46:06 +00002297 == ImplicitConversionSequence::BadConversion) {
2298 Candidate.Viable = false;
2299 return;
2300 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002301 }
2302
2303 // Determine the implicit conversion sequences for each of the
2304 // arguments.
2305 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2306 if (ArgIdx < NumArgsInProto) {
2307 // (C++ 13.3.2p3): for F to be a viable function, there shall
2308 // exist for each argument an implicit conversion sequence
2309 // (13.3.3.1) that converts that argument to the corresponding
2310 // parameter of F.
2311 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002312 Candidate.Conversions[ArgIdx + 1]
2313 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002314 SuppressUserConversions, ForceRValue,
Anders Carlsson08972922009-08-28 15:33:32 +00002315 /*InOverloadResolution=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00002316 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002317 == ImplicitConversionSequence::BadConversion) {
2318 Candidate.Viable = false;
2319 break;
2320 }
2321 } else {
2322 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2323 // argument for which there is no corresponding parameter is
2324 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002325 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002326 = ImplicitConversionSequence::EllipsisConversion;
2327 }
2328 }
2329}
2330
Douglas Gregor6b906862009-08-21 00:16:32 +00002331/// \brief Add a C++ member function template as a candidate to the candidate
2332/// set, using template argument deduction to produce an appropriate member
2333/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002334void
Douglas Gregor6b906862009-08-21 00:16:32 +00002335Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2336 bool HasExplicitTemplateArgs,
2337 const TemplateArgument *ExplicitTemplateArgs,
2338 unsigned NumExplicitTemplateArgs,
2339 Expr *Object, Expr **Args, unsigned NumArgs,
2340 OverloadCandidateSet& CandidateSet,
2341 bool SuppressUserConversions,
2342 bool ForceRValue) {
2343 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002344 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00002345 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002346 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00002347 // 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
2355 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2356 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2357 Args, NumArgs, Specialization, Info)) {
2358 // 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 }
Mike Stump1eb44332009-09-09 15:08:12 +00002363
Douglas Gregor6b906862009-08-21 00:16:32 +00002364 // Add the function template specialization produced by template argument
2365 // deduction as a candidate.
2366 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00002367 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00002368 "Specialization is not a member function?");
Mike Stump1eb44332009-09-09 15:08:12 +00002369 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002370 CandidateSet, SuppressUserConversions, ForceRValue);
2371}
2372
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002373/// \brief Add a C++ function template specialization as a candidate
2374/// in the candidate set, using template argument deduction to produce
2375/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002376void
Douglas Gregore53060f2009-06-25 22:08:12 +00002377Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002378 bool HasExplicitTemplateArgs,
2379 const TemplateArgument *ExplicitTemplateArgs,
2380 unsigned NumExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002381 Expr **Args, unsigned NumArgs,
2382 OverloadCandidateSet& CandidateSet,
2383 bool SuppressUserConversions,
2384 bool ForceRValue) {
2385 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002386 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00002387 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002388 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00002389 // candidate functions in the usual way.113) A given name can refer to one
2390 // or more function templates and also to a set of overloaded non-template
2391 // functions. In such a case, the candidate functions generated from each
2392 // function template are combined with the set of non-template candidate
2393 // functions.
2394 TemplateDeductionInfo Info(Context);
2395 FunctionDecl *Specialization = 0;
2396 if (TemplateDeductionResult Result
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002397 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2398 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2399 Args, NumArgs, Specialization, Info)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002400 // FIXME: Record what happened with template argument deduction, so
2401 // that we can give the user a beautiful diagnostic.
2402 (void)Result;
2403 return;
2404 }
Mike Stump1eb44332009-09-09 15:08:12 +00002405
Douglas Gregore53060f2009-06-25 22:08:12 +00002406 // Add the function template specialization produced by template argument
2407 // deduction as a candidate.
2408 assert(Specialization && "Missing function template specialization?");
2409 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2410 SuppressUserConversions, ForceRValue);
2411}
Mike Stump1eb44332009-09-09 15:08:12 +00002412
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002413/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00002414/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002415/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00002416/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002417/// (which may or may not be the same type as the type that the
2418/// conversion function produces).
2419void
2420Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2421 Expr *From, QualType ToType,
2422 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002423 assert(!Conversion->getDescribedFunctionTemplate() &&
2424 "Conversion function templates use AddTemplateConversionCandidate");
2425
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002426 // Add this candidate
2427 CandidateSet.push_back(OverloadCandidate());
2428 OverloadCandidate& Candidate = CandidateSet.back();
2429 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002430 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002431 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002432 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump1eb44332009-09-09 15:08:12 +00002433 Candidate.FinalConversion.FromTypePtr
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002434 = Conversion->getConversionType().getAsOpaquePtr();
2435 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2436
Douglas Gregor96176b32008-11-18 23:14:02 +00002437 // Determine the implicit conversion sequence for the implicit
2438 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002439 Candidate.Viable = true;
2440 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00002441 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002442 // Conversion functions to a different type in the base class is visible in
2443 // the derived class. So, a derived to base conversion should not participate
2444 // in overload resolution.
2445 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2446 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump1eb44332009-09-09 15:08:12 +00002447 if (Candidate.Conversions[0].ConversionKind
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002448 == ImplicitConversionSequence::BadConversion) {
2449 Candidate.Viable = false;
2450 return;
2451 }
2452
2453 // To determine what the conversion from the result of calling the
2454 // conversion function to the type we're eventually trying to
2455 // convert to (ToType), we need to synthesize a call to the
2456 // conversion function and attempt copy initialization from it. This
2457 // makes sure that we get the right semantics with respect to
2458 // lvalues/rvalues and the type. Fortunately, we can allocate this
2459 // call on the stack and we don't need its arguments to be
2460 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00002461 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002462 SourceLocation());
2463 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002464 CastExpr::CK_Unknown,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002465 &ConversionRef, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002466
2467 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00002468 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2469 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00002470 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002471 Conversion->getConversionType().getNonReferenceType(),
2472 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002473 ImplicitConversionSequence ICS =
2474 TryCopyInitialization(&Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002475 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002476 /*ForceRValue=*/false,
2477 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002478
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002479 switch (ICS.ConversionKind) {
2480 case ImplicitConversionSequence::StandardConversion:
2481 Candidate.FinalConversion = ICS.Standard;
2482 break;
2483
2484 case ImplicitConversionSequence::BadConversion:
2485 Candidate.Viable = false;
2486 break;
2487
2488 default:
Mike Stump1eb44332009-09-09 15:08:12 +00002489 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002490 "Can only end up with a standard conversion sequence or failure");
2491 }
2492}
2493
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002494/// \brief Adds a conversion function template specialization
2495/// candidate to the overload set, using template argument deduction
2496/// to deduce the template arguments of the conversion function
2497/// template from the type that we are converting to (C++
2498/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00002499void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002500Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2501 Expr *From, QualType ToType,
2502 OverloadCandidateSet &CandidateSet) {
2503 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2504 "Only conversion function templates permitted here");
2505
2506 TemplateDeductionInfo Info(Context);
2507 CXXConversionDecl *Specialization = 0;
2508 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00002509 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002510 Specialization, Info)) {
2511 // FIXME: Record what happened with template argument deduction, so
2512 // that we can give the user a beautiful diagnostic.
2513 (void)Result;
2514 return;
2515 }
Mike Stump1eb44332009-09-09 15:08:12 +00002516
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002517 // Add the conversion function template specialization produced by
2518 // template argument deduction as a candidate.
2519 assert(Specialization && "Missing function template specialization?");
2520 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2521}
2522
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002523/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2524/// converts the given @c Object to a function pointer via the
2525/// conversion function @c Conversion, and then attempts to call it
2526/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2527/// the type of function that we'll eventually be calling.
2528void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor72564e72009-02-26 23:50:07 +00002529 const FunctionProtoType *Proto,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002530 Expr *Object, Expr **Args, unsigned NumArgs,
2531 OverloadCandidateSet& CandidateSet) {
2532 CandidateSet.push_back(OverloadCandidate());
2533 OverloadCandidate& Candidate = CandidateSet.back();
2534 Candidate.Function = 0;
2535 Candidate.Surrogate = Conversion;
2536 Candidate.Viable = true;
2537 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002538 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002539 Candidate.Conversions.resize(NumArgs + 1);
2540
2541 // Determine the implicit conversion sequence for the implicit
2542 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00002543 ImplicitConversionSequence ObjectInit
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002544 = TryObjectArgumentInitialization(Object, Conversion);
2545 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2546 Candidate.Viable = false;
2547 return;
2548 }
2549
2550 // The first conversion is actually a user-defined conversion whose
2551 // first conversion is ObjectInit's standard conversion (which is
2552 // effectively a reference binding). Record it as such.
Mike Stump1eb44332009-09-09 15:08:12 +00002553 Candidate.Conversions[0].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002554 = ImplicitConversionSequence::UserDefinedConversion;
2555 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2556 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00002557 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002558 = Candidate.Conversions[0].UserDefined.Before;
2559 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2560
Mike Stump1eb44332009-09-09 15:08:12 +00002561 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002562 unsigned NumArgsInProto = Proto->getNumArgs();
2563
2564 // (C++ 13.3.2p2): A candidate function having fewer than m
2565 // parameters is viable only if it has an ellipsis in its parameter
2566 // list (8.3.5).
2567 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2568 Candidate.Viable = false;
2569 return;
2570 }
2571
2572 // Function types don't have any default arguments, so just check if
2573 // we have enough arguments.
2574 if (NumArgs < NumArgsInProto) {
2575 // Not enough arguments.
2576 Candidate.Viable = false;
2577 return;
2578 }
2579
2580 // Determine the implicit conversion sequences for each of the
2581 // arguments.
2582 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2583 if (ArgIdx < NumArgsInProto) {
2584 // (C++ 13.3.2p3): for F to be a viable function, there shall
2585 // exist for each argument an implicit conversion sequence
2586 // (13.3.3.1) that converts that argument to the corresponding
2587 // parameter of F.
2588 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002589 Candidate.Conversions[ArgIdx + 1]
2590 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002591 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002592 /*ForceRValue=*/false,
2593 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002594 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002595 == ImplicitConversionSequence::BadConversion) {
2596 Candidate.Viable = false;
2597 break;
2598 }
2599 } else {
2600 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2601 // argument for which there is no corresponding parameter is
2602 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002603 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002604 = ImplicitConversionSequence::EllipsisConversion;
2605 }
2606 }
2607}
2608
Mike Stump390b4cc2009-05-16 07:39:55 +00002609// FIXME: This will eventually be removed, once we've migrated all of the
2610// operator overloading logic over to the scheme used by binary operators, which
2611// works for template instantiation.
Douglas Gregor063daf62009-03-13 18:40:31 +00002612void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002613 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00002614 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002615 OverloadCandidateSet& CandidateSet,
2616 SourceRange OpRange) {
Douglas Gregor063daf62009-03-13 18:40:31 +00002617
2618 FunctionSet Functions;
2619
2620 QualType T1 = Args[0]->getType();
2621 QualType T2;
2622 if (NumArgs > 1)
2623 T2 = Args[1]->getType();
2624
2625 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002626 if (S)
2627 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00002628 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2629 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2630 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2631 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2632}
2633
2634/// \brief Add overload candidates for overloaded operators that are
2635/// member functions.
2636///
2637/// Add the overloaded operator candidates that are member functions
2638/// for the operator Op that was used in an operator expression such
2639/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2640/// CandidateSet will store the added overload candidates. (C++
2641/// [over.match.oper]).
2642void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2643 SourceLocation OpLoc,
2644 Expr **Args, unsigned NumArgs,
2645 OverloadCandidateSet& CandidateSet,
2646 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002647 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2648
2649 // C++ [over.match.oper]p3:
2650 // For a unary operator @ with an operand of a type whose
2651 // cv-unqualified version is T1, and for a binary operator @ with
2652 // a left operand of a type whose cv-unqualified version is T1 and
2653 // a right operand of a type whose cv-unqualified version is T2,
2654 // three sets of candidate functions, designated member
2655 // candidates, non-member candidates and built-in candidates, are
2656 // constructed as follows:
2657 QualType T1 = Args[0]->getType();
2658 QualType T2;
2659 if (NumArgs > 1)
2660 T2 = Args[1]->getType();
2661
2662 // -- If T1 is a class type, the set of member candidates is the
2663 // result of the qualified lookup of T1::operator@
2664 // (13.3.1.1.1); otherwise, the set of member candidates is
2665 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00002666 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002667 // Complete the type if it can be completed. Otherwise, we're done.
2668 if (RequireCompleteType(OpLoc, T1, PartialDiagnostic(0)))
2669 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002670
2671 LookupResult Operators = LookupQualifiedName(T1Rec->getDecl(), OpName,
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002672 LookupOrdinaryName, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002673 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002674 OperEnd = Operators.end();
2675 Oper != OperEnd;
2676 ++Oper)
Mike Stump1eb44332009-09-09 15:08:12 +00002677 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002678 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor96176b32008-11-18 23:14:02 +00002679 /*SuppressUserConversions=*/false);
Douglas Gregor96176b32008-11-18 23:14:02 +00002680 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002681}
2682
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002683/// AddBuiltinCandidate - Add a candidate for a built-in
2684/// operator. ResultTy and ParamTys are the result and parameter types
2685/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002686/// arguments being passed to the candidate. IsAssignmentOperator
2687/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002688/// operator. NumContextualBoolArguments is the number of arguments
2689/// (at the beginning of the argument list) that will be contextually
2690/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00002691void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002692 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002693 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002694 bool IsAssignmentOperator,
2695 unsigned NumContextualBoolArguments) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002696 // Add this candidate
2697 CandidateSet.push_back(OverloadCandidate());
2698 OverloadCandidate& Candidate = CandidateSet.back();
2699 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00002700 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002701 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002702 Candidate.BuiltinTypes.ResultTy = ResultTy;
2703 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2704 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2705
2706 // Determine the implicit conversion sequences for each of the
2707 // arguments.
2708 Candidate.Viable = true;
2709 Candidate.Conversions.resize(NumArgs);
2710 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002711 // C++ [over.match.oper]p4:
2712 // For the built-in assignment operators, conversions of the
2713 // left operand are restricted as follows:
2714 // -- no temporaries are introduced to hold the left operand, and
2715 // -- no user-defined conversions are applied to the left
2716 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00002717 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002718 //
2719 // We block these conversions by turning off user-defined
2720 // conversions, since that is the only way that initialization of
2721 // a reference to a non-class type can occur from something that
2722 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002723 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00002724 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002725 "Contextual conversion to bool requires bool type");
2726 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2727 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002728 Candidate.Conversions[ArgIdx]
2729 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00002730 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002731 /*ForceRValue=*/false,
2732 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002733 }
Mike Stump1eb44332009-09-09 15:08:12 +00002734 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002735 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002736 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002737 break;
2738 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002739 }
2740}
2741
2742/// BuiltinCandidateTypeSet - A set of types that will be used for the
2743/// candidate operator functions for built-in operators (C++
2744/// [over.built]). The types are separated into pointer types and
2745/// enumeration types.
2746class BuiltinCandidateTypeSet {
2747 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002748 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002749
2750 /// PointerTypes - The set of pointer types that will be used in the
2751 /// built-in candidates.
2752 TypeSet PointerTypes;
2753
Sebastian Redl78eb8742009-04-19 21:53:20 +00002754 /// MemberPointerTypes - The set of member pointer types that will be
2755 /// used in the built-in candidates.
2756 TypeSet MemberPointerTypes;
2757
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002758 /// EnumerationTypes - The set of enumeration types that will be
2759 /// used in the built-in candidates.
2760 TypeSet EnumerationTypes;
2761
Douglas Gregor5842ba92009-08-24 15:23:48 +00002762 /// Sema - The semantic analysis instance where we are building the
2763 /// candidate type set.
2764 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00002765
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002766 /// Context - The AST context in which we will build the type sets.
2767 ASTContext &Context;
2768
Sebastian Redl78eb8742009-04-19 21:53:20 +00002769 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2770 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002771
2772public:
2773 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002774 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002775
Mike Stump1eb44332009-09-09 15:08:12 +00002776 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00002777 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002778
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002779 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2780 bool AllowExplicitConversions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002781
2782 /// pointer_begin - First pointer type found;
2783 iterator pointer_begin() { return PointerTypes.begin(); }
2784
Sebastian Redl78eb8742009-04-19 21:53:20 +00002785 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002786 iterator pointer_end() { return PointerTypes.end(); }
2787
Sebastian Redl78eb8742009-04-19 21:53:20 +00002788 /// member_pointer_begin - First member pointer type found;
2789 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2790
2791 /// member_pointer_end - Past the last member pointer type found;
2792 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2793
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002794 /// enumeration_begin - First enumeration type found;
2795 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2796
Sebastian Redl78eb8742009-04-19 21:53:20 +00002797 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002798 iterator enumeration_end() { return EnumerationTypes.end(); }
2799};
2800
Sebastian Redl78eb8742009-04-19 21:53:20 +00002801/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002802/// the set of pointer types along with any more-qualified variants of
2803/// that type. For example, if @p Ty is "int const *", this routine
2804/// will add "int const *", "int const volatile *", "int const
2805/// restrict *", and "int const volatile restrict *" to the set of
2806/// pointer types. Returns true if the add of @p Ty itself succeeded,
2807/// false otherwise.
Sebastian Redl78eb8742009-04-19 21:53:20 +00002808bool
2809BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002810 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002811 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002812 return false;
2813
Ted Kremenek6217b802009-07-29 21:53:49 +00002814 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002815 QualType PointeeTy = PointerTy->getPointeeType();
2816 // FIXME: Optimize this so that we don't keep trying to add the same types.
2817
Mike Stump390b4cc2009-05-16 07:39:55 +00002818 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2819 // pointer conversions that don't cast away constness?
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002820 if (!PointeeTy.isConstQualified())
Sebastian Redl78eb8742009-04-19 21:53:20 +00002821 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002822 (Context.getPointerType(PointeeTy.withConst()));
2823 if (!PointeeTy.isVolatileQualified())
Sebastian Redl78eb8742009-04-19 21:53:20 +00002824 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002825 (Context.getPointerType(PointeeTy.withVolatile()));
2826 if (!PointeeTy.isRestrictQualified())
Sebastian Redl78eb8742009-04-19 21:53:20 +00002827 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002828 (Context.getPointerType(PointeeTy.withRestrict()));
2829 }
2830
2831 return true;
2832}
2833
Sebastian Redl78eb8742009-04-19 21:53:20 +00002834/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2835/// to the set of pointer types along with any more-qualified variants of
2836/// that type. For example, if @p Ty is "int const *", this routine
2837/// will add "int const *", "int const volatile *", "int const
2838/// restrict *", and "int const volatile restrict *" to the set of
2839/// pointer types. Returns true if the add of @p Ty itself succeeded,
2840/// false otherwise.
2841bool
2842BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2843 QualType Ty) {
2844 // Insert this type.
2845 if (!MemberPointerTypes.insert(Ty))
2846 return false;
2847
Ted Kremenek6217b802009-07-29 21:53:49 +00002848 if (const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>()) {
Sebastian Redl78eb8742009-04-19 21:53:20 +00002849 QualType PointeeTy = PointerTy->getPointeeType();
2850 const Type *ClassTy = PointerTy->getClass();
2851 // FIXME: Optimize this so that we don't keep trying to add the same types.
2852
2853 if (!PointeeTy.isConstQualified())
2854 AddMemberPointerWithMoreQualifiedTypeVariants
2855 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2856 if (!PointeeTy.isVolatileQualified())
2857 AddMemberPointerWithMoreQualifiedTypeVariants
2858 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2859 if (!PointeeTy.isRestrictQualified())
2860 AddMemberPointerWithMoreQualifiedTypeVariants
2861 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2862 }
2863
2864 return true;
2865}
2866
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002867/// AddTypesConvertedFrom - Add each of the types to which the type @p
2868/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00002869/// primarily interested in pointer types and enumeration types. We also
2870/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002871/// AllowUserConversions is true if we should look at the conversion
2872/// functions of a class type, and AllowExplicitConversions if we
2873/// should also include the explicit conversion functions of a class
2874/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00002875void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002876BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2877 bool AllowUserConversions,
2878 bool AllowExplicitConversions) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002879 // Only deal with canonical types.
2880 Ty = Context.getCanonicalType(Ty);
2881
2882 // Look through reference types; they aren't part of the type of an
2883 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00002884 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002885 Ty = RefTy->getPointeeType();
2886
2887 // We don't care about qualifiers on the type.
2888 Ty = Ty.getUnqualifiedType();
2889
Ted Kremenek6217b802009-07-29 21:53:49 +00002890 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002891 QualType PointeeTy = PointerTy->getPointeeType();
2892
2893 // Insert our type, and its more-qualified variants, into the set
2894 // of types.
Sebastian Redl78eb8742009-04-19 21:53:20 +00002895 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002896 return;
2897
2898 // Add 'cv void*' to our set of types.
2899 if (!Ty->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002900 QualType QualVoid
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002901 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl78eb8742009-04-19 21:53:20 +00002902 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002903 }
2904
2905 // If this is a pointer to a class type, add pointers to its bases
2906 // (with the same level of cv-qualification as the original
2907 // derived class, of course).
Ted Kremenek6217b802009-07-29 21:53:49 +00002908 if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002909 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2910 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2911 Base != ClassDecl->bases_end(); ++Base) {
2912 QualType BaseTy = Context.getCanonicalType(Base->getType());
2913 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2914
2915 // Add the pointer type, recursively, so that we get all of
2916 // the indirect base classes, too.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002917 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002918 }
2919 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00002920 } else if (Ty->isMemberPointerType()) {
2921 // Member pointers are far easier, since the pointee can't be converted.
2922 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2923 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002924 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00002925 EnumerationTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002926 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002927 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002928 if (SemaRef.RequireCompleteType(SourceLocation(), Ty, 0)) {
2929 // No conversion functions in incomplete types.
2930 return;
2931 }
Mike Stump1eb44332009-09-09 15:08:12 +00002932
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002933 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2934 // FIXME: Visit conversion functions in the base classes, too.
Mike Stump1eb44332009-09-09 15:08:12 +00002935 OverloadedFunctionDecl *Conversions
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002936 = ClassDecl->getConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00002937 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002938 = Conversions->function_begin();
2939 Func != Conversions->function_end(); ++Func) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002940 CXXConversionDecl *Conv;
2941 FunctionTemplateDecl *ConvTemplate;
2942 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
2943
Mike Stump1eb44332009-09-09 15:08:12 +00002944 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002945 // about which builtin types we can convert to.
2946 if (ConvTemplate)
2947 continue;
2948
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002949 if (AllowExplicitConversions || !Conv->isExplicit())
2950 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002951 }
2952 }
2953 }
2954}
2955
Douglas Gregor19b7b152009-08-24 13:43:27 +00002956/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
2957/// the volatile- and non-volatile-qualified assignment operators for the
2958/// given type to the candidate set.
2959static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
2960 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00002961 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00002962 unsigned NumArgs,
2963 OverloadCandidateSet &CandidateSet) {
2964 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002965
Douglas Gregor19b7b152009-08-24 13:43:27 +00002966 // T& operator=(T&, T)
2967 ParamTypes[0] = S.Context.getLValueReferenceType(T);
2968 ParamTypes[1] = T;
2969 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2970 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00002971
Douglas Gregor19b7b152009-08-24 13:43:27 +00002972 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
2973 // volatile T& operator=(volatile T&, T)
2974 ParamTypes[0] = S.Context.getLValueReferenceType(T.withVolatile());
2975 ParamTypes[1] = T;
2976 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00002977 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00002978 }
2979}
Mike Stump1eb44332009-09-09 15:08:12 +00002980
Douglas Gregor74253732008-11-19 15:42:04 +00002981/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2982/// operator overloads to the candidate set (C++ [over.built]), based
2983/// on the operator @p Op and the arguments given. For example, if the
2984/// operator is a binary '+', this routine might add "int
2985/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002986void
Mike Stump1eb44332009-09-09 15:08:12 +00002987Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor74253732008-11-19 15:42:04 +00002988 Expr **Args, unsigned NumArgs,
2989 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002990 // The set of "promoted arithmetic types", which are the arithmetic
2991 // types are that preserved by promotion (C++ [over.built]p2). Note
2992 // that the first few of these types are the promoted integral
2993 // types; these types need to be first.
2994 // FIXME: What about complex?
2995 const unsigned FirstIntegralType = 0;
2996 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00002997 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002998 LastPromotedIntegralType = 13;
2999 const unsigned FirstPromotedArithmeticType = 7,
3000 LastPromotedArithmeticType = 16;
3001 const unsigned NumArithmeticTypes = 16;
3002 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00003003 Context.BoolTy, Context.CharTy, Context.WCharTy,
3004// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003005 Context.SignedCharTy, Context.ShortTy,
3006 Context.UnsignedCharTy, Context.UnsignedShortTy,
3007 Context.IntTy, Context.LongTy, Context.LongLongTy,
3008 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3009 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3010 };
3011
3012 // Find all of the types that the arguments can convert to, but only
3013 // if the operator we're looking at has built-in operator candidates
3014 // that make use of these types.
Douglas Gregor5842ba92009-08-24 15:23:48 +00003015 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003016 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3017 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00003018 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003019 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00003020 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003021 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor74253732008-11-19 15:42:04 +00003022 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003023 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3024 true,
3025 (Op == OO_Exclaim ||
3026 Op == OO_AmpAmp ||
3027 Op == OO_PipePipe));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003028 }
3029
3030 bool isComparison = false;
3031 switch (Op) {
3032 case OO_None:
3033 case NUM_OVERLOADED_OPERATORS:
3034 assert(false && "Expected an overloaded operator");
3035 break;
3036
Douglas Gregor74253732008-11-19 15:42:04 +00003037 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00003038 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00003039 goto UnaryStar;
3040 else
3041 goto BinaryStar;
3042 break;
3043
3044 case OO_Plus: // '+' is either unary or binary
3045 if (NumArgs == 1)
3046 goto UnaryPlus;
3047 else
3048 goto BinaryPlus;
3049 break;
3050
3051 case OO_Minus: // '-' is either unary or binary
3052 if (NumArgs == 1)
3053 goto UnaryMinus;
3054 else
3055 goto BinaryMinus;
3056 break;
3057
3058 case OO_Amp: // '&' is either unary or binary
3059 if (NumArgs == 1)
3060 goto UnaryAmp;
3061 else
3062 goto BinaryAmp;
3063
3064 case OO_PlusPlus:
3065 case OO_MinusMinus:
3066 // C++ [over.built]p3:
3067 //
3068 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3069 // is either volatile or empty, there exist candidate operator
3070 // functions of the form
3071 //
3072 // VQ T& operator++(VQ T&);
3073 // T operator++(VQ T&, int);
3074 //
3075 // C++ [over.built]p4:
3076 //
3077 // For every pair (T, VQ), where T is an arithmetic type other
3078 // than bool, and VQ is either volatile or empty, there exist
3079 // candidate operator functions of the form
3080 //
3081 // VQ T& operator--(VQ T&);
3082 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00003083 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00003084 Arith < NumArithmeticTypes; ++Arith) {
3085 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00003086 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003087 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00003088
3089 // Non-volatile version.
3090 if (NumArgs == 1)
3091 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3092 else
3093 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3094
3095 // Volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003096 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor74253732008-11-19 15:42:04 +00003097 if (NumArgs == 1)
3098 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3099 else
3100 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3101 }
3102
3103 // C++ [over.built]p5:
3104 //
3105 // For every pair (T, VQ), where T is a cv-qualified or
3106 // cv-unqualified object type, and VQ is either volatile or
3107 // empty, there exist candidate operator functions of the form
3108 //
3109 // T*VQ& operator++(T*VQ&);
3110 // T*VQ& operator--(T*VQ&);
3111 // T* operator++(T*VQ&, int);
3112 // T* operator--(T*VQ&, int);
3113 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3114 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3115 // Skip pointer types that aren't pointers to object types.
Ted Kremenek6217b802009-07-29 21:53:49 +00003116 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00003117 continue;
3118
Mike Stump1eb44332009-09-09 15:08:12 +00003119 QualType ParamTypes[2] = {
3120 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00003121 };
Mike Stump1eb44332009-09-09 15:08:12 +00003122
Douglas Gregor74253732008-11-19 15:42:04 +00003123 // Without volatile
3124 if (NumArgs == 1)
3125 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3126 else
3127 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3128
3129 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3130 // With volatile
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003131 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor74253732008-11-19 15:42:04 +00003132 if (NumArgs == 1)
3133 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3134 else
3135 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3136 }
3137 }
3138 break;
3139
3140 UnaryStar:
3141 // C++ [over.built]p6:
3142 // For every cv-qualified or cv-unqualified object type T, there
3143 // exist candidate operator functions of the form
3144 //
3145 // T& operator*(T*);
3146 //
3147 // C++ [over.built]p7:
3148 // For every function type T, there exist candidate operator
3149 // functions of the form
3150 // T& operator*(T*);
3151 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3152 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3153 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00003154 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003155 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00003156 &ParamTy, Args, 1, CandidateSet);
3157 }
3158 break;
3159
3160 UnaryPlus:
3161 // C++ [over.built]p8:
3162 // For every type T, there exist candidate operator functions of
3163 // the form
3164 //
3165 // T* operator+(T*);
3166 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3167 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3168 QualType ParamTy = *Ptr;
3169 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3170 }
Mike Stump1eb44332009-09-09 15:08:12 +00003171
Douglas Gregor74253732008-11-19 15:42:04 +00003172 // Fall through
3173
3174 UnaryMinus:
3175 // C++ [over.built]p9:
3176 // For every promoted arithmetic type T, there exist candidate
3177 // operator functions of the form
3178 //
3179 // T operator+(T);
3180 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003181 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00003182 Arith < LastPromotedArithmeticType; ++Arith) {
3183 QualType ArithTy = ArithmeticTypes[Arith];
3184 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3185 }
3186 break;
3187
3188 case OO_Tilde:
3189 // C++ [over.built]p10:
3190 // For every promoted integral type T, there exist candidate
3191 // operator functions of the form
3192 //
3193 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003194 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00003195 Int < LastPromotedIntegralType; ++Int) {
3196 QualType IntTy = ArithmeticTypes[Int];
3197 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3198 }
3199 break;
3200
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003201 case OO_New:
3202 case OO_Delete:
3203 case OO_Array_New:
3204 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003205 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00003206 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003207 break;
3208
3209 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00003210 UnaryAmp:
3211 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003212 // C++ [over.match.oper]p3:
3213 // -- For the operator ',', the unary operator '&', or the
3214 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003215 break;
3216
Douglas Gregor19b7b152009-08-24 13:43:27 +00003217 case OO_EqualEqual:
3218 case OO_ExclaimEqual:
3219 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00003220 // For every pointer to member type T, there exist candidate operator
3221 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00003222 //
3223 // bool operator==(T,T);
3224 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00003225 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00003226 MemPtr = CandidateTypes.member_pointer_begin(),
3227 MemPtrEnd = CandidateTypes.member_pointer_end();
3228 MemPtr != MemPtrEnd;
3229 ++MemPtr) {
3230 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3231 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3232 }
Mike Stump1eb44332009-09-09 15:08:12 +00003233
Douglas Gregor19b7b152009-08-24 13:43:27 +00003234 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00003235
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003236 case OO_Less:
3237 case OO_Greater:
3238 case OO_LessEqual:
3239 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003240 // C++ [over.built]p15:
3241 //
3242 // For every pointer or enumeration type T, there exist
3243 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003244 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003245 // bool operator<(T, T);
3246 // bool operator>(T, T);
3247 // bool operator<=(T, T);
3248 // bool operator>=(T, T);
3249 // bool operator==(T, T);
3250 // bool operator!=(T, T);
3251 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3252 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3253 QualType ParamTypes[2] = { *Ptr, *Ptr };
3254 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3255 }
Mike Stump1eb44332009-09-09 15:08:12 +00003256 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003257 = CandidateTypes.enumeration_begin();
3258 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3259 QualType ParamTypes[2] = { *Enum, *Enum };
3260 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3261 }
3262
3263 // Fall through.
3264 isComparison = true;
3265
Douglas Gregor74253732008-11-19 15:42:04 +00003266 BinaryPlus:
3267 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003268 if (!isComparison) {
3269 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3270
3271 // C++ [over.built]p13:
3272 //
3273 // For every cv-qualified or cv-unqualified object type T
3274 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003275 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003276 // T* operator+(T*, ptrdiff_t);
3277 // T& operator[](T*, ptrdiff_t); [BELOW]
3278 // T* operator-(T*, ptrdiff_t);
3279 // T* operator+(ptrdiff_t, T*);
3280 // T& operator[](ptrdiff_t, T*); [BELOW]
3281 //
3282 // C++ [over.built]p14:
3283 //
3284 // For every T, where T is a pointer to object type, there
3285 // exist candidate operator functions of the form
3286 //
3287 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00003288 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003289 = CandidateTypes.pointer_begin();
3290 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3291 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3292
3293 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3294 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3295
3296 if (Op == OO_Plus) {
3297 // T* operator+(ptrdiff_t, T*);
3298 ParamTypes[0] = ParamTypes[1];
3299 ParamTypes[1] = *Ptr;
3300 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3301 } else {
3302 // ptrdiff_t operator-(T, T);
3303 ParamTypes[1] = *Ptr;
3304 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3305 Args, 2, CandidateSet);
3306 }
3307 }
3308 }
3309 // Fall through
3310
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003311 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00003312 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003313 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003314 // C++ [over.built]p12:
3315 //
3316 // For every pair of promoted arithmetic types L and R, there
3317 // exist candidate operator functions of the form
3318 //
3319 // LR operator*(L, R);
3320 // LR operator/(L, R);
3321 // LR operator+(L, R);
3322 // LR operator-(L, R);
3323 // bool operator<(L, R);
3324 // bool operator>(L, R);
3325 // bool operator<=(L, R);
3326 // bool operator>=(L, R);
3327 // bool operator==(L, R);
3328 // bool operator!=(L, R);
3329 //
3330 // where LR is the result of the usual arithmetic conversions
3331 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003332 //
3333 // C++ [over.built]p24:
3334 //
3335 // For every pair of promoted arithmetic types L and R, there exist
3336 // candidate operator functions of the form
3337 //
3338 // LR operator?(bool, L, R);
3339 //
3340 // where LR is the result of the usual arithmetic conversions
3341 // between types L and R.
3342 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003343 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003344 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003345 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003346 Right < LastPromotedArithmeticType; ++Right) {
3347 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00003348 QualType Result
3349 = isComparison
3350 ? Context.BoolTy
3351 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003352 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3353 }
3354 }
3355 break;
3356
3357 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00003358 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003359 case OO_Caret:
3360 case OO_Pipe:
3361 case OO_LessLess:
3362 case OO_GreaterGreater:
3363 // C++ [over.built]p17:
3364 //
3365 // For every pair of promoted integral types L and R, there
3366 // exist candidate operator functions of the form
3367 //
3368 // LR operator%(L, R);
3369 // LR operator&(L, R);
3370 // LR operator^(L, R);
3371 // LR operator|(L, R);
3372 // L operator<<(L, R);
3373 // L operator>>(L, R);
3374 //
3375 // where LR is the result of the usual arithmetic conversions
3376 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00003377 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003378 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003379 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003380 Right < LastPromotedIntegralType; ++Right) {
3381 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3382 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3383 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00003384 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003385 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3386 }
3387 }
3388 break;
3389
3390 case OO_Equal:
3391 // C++ [over.built]p20:
3392 //
3393 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00003394 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003395 // empty, there exist candidate operator functions of the form
3396 //
3397 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003398 for (BuiltinCandidateTypeSet::iterator
3399 Enum = CandidateTypes.enumeration_begin(),
3400 EnumEnd = CandidateTypes.enumeration_end();
3401 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00003402 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003403 CandidateSet);
3404 for (BuiltinCandidateTypeSet::iterator
3405 MemPtr = CandidateTypes.member_pointer_begin(),
3406 MemPtrEnd = CandidateTypes.member_pointer_end();
3407 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00003408 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003409 CandidateSet);
3410 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003411
3412 case OO_PlusEqual:
3413 case OO_MinusEqual:
3414 // C++ [over.built]p19:
3415 //
3416 // For every pair (T, VQ), where T is any type and VQ is either
3417 // volatile or empty, there exist candidate operator functions
3418 // of the form
3419 //
3420 // T*VQ& operator=(T*VQ&, T*);
3421 //
3422 // C++ [over.built]p21:
3423 //
3424 // For every pair (T, VQ), where T is a cv-qualified or
3425 // cv-unqualified object type and VQ is either volatile or
3426 // empty, there exist candidate operator functions of the form
3427 //
3428 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3429 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3430 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3431 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3432 QualType ParamTypes[2];
3433 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3434
3435 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003436 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003437 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3438 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003439
Douglas Gregor74253732008-11-19 15:42:04 +00003440 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3441 // volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003442 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003443 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3444 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003445 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003446 }
3447 // Fall through.
3448
3449 case OO_StarEqual:
3450 case OO_SlashEqual:
3451 // C++ [over.built]p18:
3452 //
3453 // For every triple (L, VQ, R), where L is an arithmetic type,
3454 // VQ is either volatile or empty, and R is a promoted
3455 // arithmetic type, there exist candidate operator functions of
3456 // the form
3457 //
3458 // VQ L& operator=(VQ L&, R);
3459 // VQ L& operator*=(VQ L&, R);
3460 // VQ L& operator/=(VQ L&, R);
3461 // VQ L& operator+=(VQ L&, R);
3462 // VQ L& operator-=(VQ L&, R);
3463 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003464 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003465 Right < LastPromotedArithmeticType; ++Right) {
3466 QualType ParamTypes[2];
3467 ParamTypes[1] = ArithmeticTypes[Right];
3468
3469 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003470 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003471 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3472 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003473
3474 // Add this built-in operator as a candidate (VQ is 'volatile').
3475 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003476 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003477 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3478 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003479 }
3480 }
3481 break;
3482
3483 case OO_PercentEqual:
3484 case OO_LessLessEqual:
3485 case OO_GreaterGreaterEqual:
3486 case OO_AmpEqual:
3487 case OO_CaretEqual:
3488 case OO_PipeEqual:
3489 // C++ [over.built]p22:
3490 //
3491 // For every triple (L, VQ, R), where L is an integral type, VQ
3492 // is either volatile or empty, and R is a promoted integral
3493 // type, there exist candidate operator functions of the form
3494 //
3495 // VQ L& operator%=(VQ L&, R);
3496 // VQ L& operator<<=(VQ L&, R);
3497 // VQ L& operator>>=(VQ L&, R);
3498 // VQ L& operator&=(VQ L&, R);
3499 // VQ L& operator^=(VQ L&, R);
3500 // VQ L& operator|=(VQ L&, R);
3501 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003502 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003503 Right < LastPromotedIntegralType; ++Right) {
3504 QualType ParamTypes[2];
3505 ParamTypes[1] = ArithmeticTypes[Right];
3506
3507 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003508 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003509 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3510
3511 // Add this built-in operator as a candidate (VQ is 'volatile').
3512 ParamTypes[0] = ArithmeticTypes[Left];
3513 ParamTypes[0].addVolatile();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003514 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003515 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3516 }
3517 }
3518 break;
3519
Douglas Gregor74253732008-11-19 15:42:04 +00003520 case OO_Exclaim: {
3521 // C++ [over.operator]p23:
3522 //
3523 // There also exist candidate operator functions of the form
3524 //
Mike Stump1eb44332009-09-09 15:08:12 +00003525 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00003526 // bool operator&&(bool, bool); [BELOW]
3527 // bool operator||(bool, bool); [BELOW]
3528 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003529 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3530 /*IsAssignmentOperator=*/false,
3531 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00003532 break;
3533 }
3534
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003535 case OO_AmpAmp:
3536 case OO_PipePipe: {
3537 // C++ [over.operator]p23:
3538 //
3539 // There also exist candidate operator functions of the form
3540 //
Douglas Gregor74253732008-11-19 15:42:04 +00003541 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003542 // bool operator&&(bool, bool);
3543 // bool operator||(bool, bool);
3544 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003545 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3546 /*IsAssignmentOperator=*/false,
3547 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003548 break;
3549 }
3550
3551 case OO_Subscript:
3552 // C++ [over.built]p13:
3553 //
3554 // For every cv-qualified or cv-unqualified object type T there
3555 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003556 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003557 // T* operator+(T*, ptrdiff_t); [ABOVE]
3558 // T& operator[](T*, ptrdiff_t);
3559 // T* operator-(T*, ptrdiff_t); [ABOVE]
3560 // T* operator+(ptrdiff_t, T*); [ABOVE]
3561 // T& operator[](ptrdiff_t, T*);
3562 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3563 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3564 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00003565 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003566 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003567
3568 // T& operator[](T*, ptrdiff_t)
3569 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3570
3571 // T& operator[](ptrdiff_t, T*);
3572 ParamTypes[0] = ParamTypes[1];
3573 ParamTypes[1] = *Ptr;
3574 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3575 }
3576 break;
3577
3578 case OO_ArrowStar:
3579 // FIXME: No support for pointer-to-members yet.
3580 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003581
3582 case OO_Conditional:
3583 // Note that we don't consider the first argument, since it has been
3584 // contextually converted to bool long ago. The candidates below are
3585 // therefore added as binary.
3586 //
3587 // C++ [over.built]p24:
3588 // For every type T, where T is a pointer or pointer-to-member type,
3589 // there exist candidate operator functions of the form
3590 //
3591 // T operator?(bool, T, T);
3592 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003593 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3594 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3595 QualType ParamTypes[2] = { *Ptr, *Ptr };
3596 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3597 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00003598 for (BuiltinCandidateTypeSet::iterator Ptr =
3599 CandidateTypes.member_pointer_begin(),
3600 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3601 QualType ParamTypes[2] = { *Ptr, *Ptr };
3602 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3603 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003604 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003605 }
3606}
3607
Douglas Gregorfa047642009-02-04 00:32:51 +00003608/// \brief Add function candidates found via argument-dependent lookup
3609/// to the set of overloading candidates.
3610///
3611/// This routine performs argument-dependent name lookup based on the
3612/// given function name (which may also be an operator name) and adds
3613/// all of the overload candidates found by ADL to the overload
3614/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00003615void
Douglas Gregorfa047642009-02-04 00:32:51 +00003616Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3617 Expr **Args, unsigned NumArgs,
3618 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003619 FunctionSet Functions;
Douglas Gregorfa047642009-02-04 00:32:51 +00003620
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003621 // Record all of the function candidates that we've already
3622 // added to the overload set, so that we don't add those same
3623 // candidates a second time.
3624 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3625 CandEnd = CandidateSet.end();
3626 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00003627 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003628 Functions.insert(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00003629 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3630 Functions.insert(FunTmpl);
3631 }
Douglas Gregorfa047642009-02-04 00:32:51 +00003632
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003633 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregorfa047642009-02-04 00:32:51 +00003634
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003635 // Erase all of the candidates we already knew about.
3636 // FIXME: This is suboptimal. Is there a better way?
3637 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3638 CandEnd = CandidateSet.end();
3639 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00003640 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003641 Functions.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00003642 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3643 Functions.erase(FunTmpl);
3644 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003645
3646 // For each of the ADL candidates we found, add it to the overload
3647 // set.
3648 for (FunctionSet::iterator Func = Functions.begin(),
3649 FuncEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00003650 Func != FuncEnd; ++Func) {
3651 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
3652 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet);
3653 else
Mike Stump1eb44332009-09-09 15:08:12 +00003654 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003655 /*FIXME: explicit args */false, 0, 0,
3656 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00003657 }
Douglas Gregorfa047642009-02-04 00:32:51 +00003658}
3659
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003660/// isBetterOverloadCandidate - Determines whether the first overload
3661/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00003662bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003663Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump1eb44332009-09-09 15:08:12 +00003664 const OverloadCandidate& Cand2) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003665 // Define viable functions to be better candidates than non-viable
3666 // functions.
3667 if (!Cand2.Viable)
3668 return Cand1.Viable;
3669 else if (!Cand1.Viable)
3670 return false;
3671
Douglas Gregor88a35142008-12-22 05:46:06 +00003672 // C++ [over.match.best]p1:
3673 //
3674 // -- if F is a static member function, ICS1(F) is defined such
3675 // that ICS1(F) is neither better nor worse than ICS1(G) for
3676 // any function G, and, symmetrically, ICS1(G) is neither
3677 // better nor worse than ICS1(F).
3678 unsigned StartArg = 0;
3679 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3680 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003681
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003682 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00003683 // A viable function F1 is defined to be a better function than another
3684 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003685 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003686 unsigned NumArgs = Cand1.Conversions.size();
3687 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3688 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003689 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003690 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3691 Cand2.Conversions[ArgIdx])) {
3692 case ImplicitConversionSequence::Better:
3693 // Cand1 has a better conversion sequence.
3694 HasBetterConversion = true;
3695 break;
3696
3697 case ImplicitConversionSequence::Worse:
3698 // Cand1 can't be better than Cand2.
3699 return false;
3700
3701 case ImplicitConversionSequence::Indistinguishable:
3702 // Do nothing.
3703 break;
3704 }
3705 }
3706
Mike Stump1eb44332009-09-09 15:08:12 +00003707 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003708 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003709 if (HasBetterConversion)
3710 return true;
3711
Mike Stump1eb44332009-09-09 15:08:12 +00003712 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003713 // specialization, or, if not that,
3714 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3715 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3716 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003717
3718 // -- F1 and F2 are function template specializations, and the function
3719 // template for F1 is more specialized than the template for F2
3720 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003721 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00003722 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3723 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003724 if (FunctionTemplateDecl *BetterTemplate
3725 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3726 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor5d7d3752009-09-14 23:02:14 +00003727 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
3728 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003729 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003730
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003731 // -- the context is an initialization by user-defined conversion
3732 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3733 // from the return type of F1 to the destination type (i.e.,
3734 // the type of the entity being initialized) is a better
3735 // conversion sequence than the standard conversion sequence
3736 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00003737 if (Cand1.Function && Cand2.Function &&
3738 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003739 isa<CXXConversionDecl>(Cand2.Function)) {
3740 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3741 Cand2.FinalConversion)) {
3742 case ImplicitConversionSequence::Better:
3743 // Cand1 has a better conversion sequence.
3744 return true;
3745
3746 case ImplicitConversionSequence::Worse:
3747 // Cand1 can't be better than Cand2.
3748 return false;
3749
3750 case ImplicitConversionSequence::Indistinguishable:
3751 // Do nothing
3752 break;
3753 }
3754 }
3755
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003756 return false;
3757}
3758
Mike Stump1eb44332009-09-09 15:08:12 +00003759/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00003760/// within an overload candidate set.
3761///
3762/// \param CandidateSet the set of candidate functions.
3763///
3764/// \param Loc the location of the function name (or operator symbol) for
3765/// which overload resolution occurs.
3766///
Mike Stump1eb44332009-09-09 15:08:12 +00003767/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00003768/// function, Best points to the candidate function found.
3769///
3770/// \returns The result of overload resolution.
Mike Stump1eb44332009-09-09 15:08:12 +00003771Sema::OverloadingResult
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003772Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregore0762c92009-06-19 23:52:42 +00003773 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00003774 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003775 // Find the best viable function.
3776 Best = CandidateSet.end();
3777 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3778 Cand != CandidateSet.end(); ++Cand) {
3779 if (Cand->Viable) {
3780 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3781 Best = Cand;
3782 }
3783 }
3784
3785 // If we didn't find any viable functions, abort.
3786 if (Best == CandidateSet.end())
3787 return OR_No_Viable_Function;
3788
3789 // Make sure that this function is better than every other viable
3790 // function. If not, we have an ambiguity.
3791 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3792 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00003793 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003794 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003795 !isBetterOverloadCandidate(*Best, *Cand)) {
3796 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003797 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003798 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003799 }
Mike Stump1eb44332009-09-09 15:08:12 +00003800
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003801 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003802 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00003803 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003804 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003805 return OR_Deleted;
3806
Douglas Gregore0762c92009-06-19 23:52:42 +00003807 // C++ [basic.def.odr]p2:
3808 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00003809 // when referred to from a potentially-evaluated expression. [Note: this
3810 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00003811 // (clause 13), user-defined conversions (12.3.2), allocation function for
3812 // placement new (5.3.4), as well as non-default initialization (8.5).
3813 if (Best->Function)
3814 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003815 return OR_Success;
3816}
3817
3818/// PrintOverloadCandidates - When overload resolution fails, prints
3819/// diagnostic messages containing the candidates in the candidate
3820/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump1eb44332009-09-09 15:08:12 +00003821void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003822Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00003823 bool OnlyViable) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003824 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3825 LastCand = CandidateSet.end();
3826 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003827 if (Cand->Viable || !OnlyViable) {
3828 if (Cand->Function) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003829 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003830 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003831 // Deleted or "unavailable" function.
3832 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3833 << Cand->Function->isDeleted();
Douglas Gregor1fdd89b2009-09-15 20:11:42 +00003834 } else if (FunctionTemplateDecl *FunTmpl
3835 = Cand->Function->getPrimaryTemplate()) {
3836 // Function template specialization
3837 // FIXME: Give a better reason!
3838 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
3839 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
3840 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003841 } else {
3842 // Normal function
3843 // FIXME: Give a better reason!
3844 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3845 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003846 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003847 // Desugar the type of the surrogate down to a function type,
3848 // retaining as many typedefs as possible while still showing
3849 // the function type (and, therefore, its parameter types).
3850 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003851 bool isLValueReference = false;
3852 bool isRValueReference = false;
Douglas Gregor621b3932008-11-21 02:54:28 +00003853 bool isPointer = false;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003854 if (const LValueReferenceType *FnTypeRef =
Ted Kremenek6217b802009-07-29 21:53:49 +00003855 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003856 FnType = FnTypeRef->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003857 isLValueReference = true;
3858 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenek6217b802009-07-29 21:53:49 +00003859 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003860 FnType = FnTypeRef->getPointeeType();
3861 isRValueReference = true;
Douglas Gregor621b3932008-11-21 02:54:28 +00003862 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003863 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003864 FnType = FnTypePtr->getPointeeType();
3865 isPointer = true;
3866 }
3867 // Desugar down to a function type.
3868 FnType = QualType(FnType->getAsFunctionType(), 0);
3869 // Reconstruct the pointer/reference as appropriate.
3870 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003871 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3872 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor621b3932008-11-21 02:54:28 +00003873
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003874 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003875 << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003876 } else {
3877 // FIXME: We need to get the identifier in here
Mike Stump390b4cc2009-05-16 07:39:55 +00003878 // FIXME: Do we want the error message to point at the operator?
3879 // (built-ins won't have a location)
Mike Stump1eb44332009-09-09 15:08:12 +00003880 QualType FnType
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003881 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3882 Cand->BuiltinTypes.ParamTypes,
3883 Cand->Conversions.size(),
3884 false, 0);
3885
Chris Lattnerd1625842008-11-24 06:25:27 +00003886 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003887 }
3888 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003889 }
3890}
3891
Douglas Gregor904eed32008-11-10 20:40:00 +00003892/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3893/// an overloaded function (C++ [over.over]), where @p From is an
3894/// expression with overloaded function type and @p ToType is the type
3895/// we're trying to resolve to. For example:
3896///
3897/// @code
3898/// int f(double);
3899/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00003900///
Douglas Gregor904eed32008-11-10 20:40:00 +00003901/// int (*pfd)(double) = f; // selects f(double)
3902/// @endcode
3903///
3904/// This routine returns the resulting FunctionDecl if it could be
3905/// resolved, and NULL otherwise. When @p Complain is true, this
3906/// routine will emit diagnostics if there is an error.
3907FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00003908Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor904eed32008-11-10 20:40:00 +00003909 bool Complain) {
3910 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00003911 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00003912 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00003913 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003914 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00003915 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00003916 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00003917 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00003918 FunctionType = MemTypePtr->getPointeeType();
3919 IsMember = true;
3920 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003921
3922 // We only look at pointers or references to functions.
Douglas Gregor72e771f2009-07-09 17:16:51 +00003923 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor83314aa2009-07-08 20:55:45 +00003924 if (!FunctionType->isFunctionType())
Douglas Gregor904eed32008-11-10 20:40:00 +00003925 return 0;
3926
3927 // Find the actual overloaded function declaration.
3928 OverloadedFunctionDecl *Ovl = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003929
Douglas Gregor904eed32008-11-10 20:40:00 +00003930 // C++ [over.over]p1:
3931 // [...] [Note: any redundant set of parentheses surrounding the
3932 // overloaded function name is ignored (5.1). ]
3933 Expr *OvlExpr = From->IgnoreParens();
3934
3935 // C++ [over.over]p1:
3936 // [...] The overloaded function name can be preceded by the &
3937 // operator.
3938 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3939 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3940 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3941 }
3942
3943 // Try to dig out the overloaded function.
Douglas Gregor83314aa2009-07-08 20:55:45 +00003944 FunctionTemplateDecl *FunctionTemplate = 0;
3945 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00003946 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor83314aa2009-07-08 20:55:45 +00003947 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
3948 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003949
Mike Stump1eb44332009-09-09 15:08:12 +00003950 // If there's no overloaded function declaration or function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00003951 // we're done.
3952 if (!Ovl && !FunctionTemplate)
Douglas Gregor904eed32008-11-10 20:40:00 +00003953 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003954
Douglas Gregor83314aa2009-07-08 20:55:45 +00003955 OverloadIterator Fun;
3956 if (Ovl)
3957 Fun = Ovl;
3958 else
3959 Fun = FunctionTemplate;
Mike Stump1eb44332009-09-09 15:08:12 +00003960
Douglas Gregor904eed32008-11-10 20:40:00 +00003961 // Look through all of the overloaded functions, searching for one
3962 // whose type matches exactly.
Douglas Gregor00aeb522009-07-08 23:33:52 +00003963 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Mike Stump1eb44332009-09-09 15:08:12 +00003964
Douglas Gregor00aeb522009-07-08 23:33:52 +00003965 bool FoundNonTemplateFunction = false;
Douglas Gregor83314aa2009-07-08 20:55:45 +00003966 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregor904eed32008-11-10 20:40:00 +00003967 // C++ [over.over]p3:
3968 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00003969 // targets of type "pointer-to-function" or "reference-to-function."
3970 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00003971 // type "pointer-to-member-function."
3972 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00003973
Mike Stump1eb44332009-09-09 15:08:12 +00003974 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregor83314aa2009-07-08 20:55:45 +00003975 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003976 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00003977 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003978 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00003979 // static when converting to member pointer.
3980 if (Method->isStatic() == IsMember)
3981 continue;
3982 } else if (IsMember)
3983 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003984
Douglas Gregor00aeb522009-07-08 23:33:52 +00003985 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003986 // If the name is a function template, template argument deduction is
3987 // done (14.8.2.2), and if the argument deduction succeeds, the
3988 // resulting template argument list is used to generate a single
3989 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00003990 // overloaded functions considered.
Douglas Gregor83314aa2009-07-08 20:55:45 +00003991 FunctionDecl *Specialization = 0;
3992 TemplateDeductionInfo Info(Context);
3993 if (TemplateDeductionResult Result
3994 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
3995 /*FIXME:*/0, /*FIXME:*/0,
3996 FunctionType, Specialization, Info)) {
3997 // FIXME: make a note of the failed deduction for diagnostics.
3998 (void)Result;
3999 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004000 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00004001 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00004002 Matches.insert(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00004003 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor83314aa2009-07-08 20:55:45 +00004004 }
4005 }
Mike Stump1eb44332009-09-09 15:08:12 +00004006
Sebastian Redl33b399a2009-02-04 21:23:32 +00004007 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
4008 // Skip non-static functions when converting to pointer, and static
4009 // when converting to member pointer.
4010 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00004011 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004012 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00004013 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00004014
Douglas Gregore53060f2009-06-25 22:08:12 +00004015 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregor00aeb522009-07-08 23:33:52 +00004016 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00004017 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00004018 FoundNonTemplateFunction = true;
4019 }
Mike Stump1eb44332009-09-09 15:08:12 +00004020 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004021 }
4022
Douglas Gregor00aeb522009-07-08 23:33:52 +00004023 // If there were 0 or 1 matches, we're done.
4024 if (Matches.empty())
4025 return 0;
4026 else if (Matches.size() == 1)
4027 return *Matches.begin();
4028
4029 // C++ [over.over]p4:
4030 // If more than one function is selected, [...]
4031 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004032 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004033 if (FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004034 // [...] any function template specializations in the set are
4035 // eliminated if the set also contains a non-template function, [...]
4036 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
Douglas Gregor00aeb522009-07-08 23:33:52 +00004037 if ((*M)->getPrimaryTemplate() == 0)
4038 RemainingMatches.push_back(*M);
4039 } else {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004040 // [...] and any given function template specialization F1 is
4041 // eliminated if the set contains a second function template
4042 // specialization whose function template is more specialized
4043 // than the function template of F1 according to the partial
4044 // ordering rules of 14.5.5.2.
4045
4046 // The algorithm specified above is quadratic. We instead use a
4047 // two-pass algorithm (similar to the one used to identify the
4048 // best viable function in an overload set) that identifies the
4049 // best function template (if it exists).
4050 MatchIter Best = Matches.begin();
4051 MatchIter M = Best, MEnd = Matches.end();
4052 // Find the most specialized function.
4053 for (++M; M != MEnd; ++M)
4054 if (getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4055 (*Best)->getPrimaryTemplate(),
Douglas Gregor8a514912009-09-14 18:39:43 +00004056 TPOC_Other)
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004057 == (*M)->getPrimaryTemplate())
4058 Best = M;
4059
4060 // Determine whether this function template is more specialized
4061 // that all of the others.
4062 bool Ambiguous = false;
4063 for (M = Matches.begin(); M != MEnd; ++M) {
4064 if (M != Best &&
4065 getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4066 (*Best)->getPrimaryTemplate(),
Douglas Gregor8a514912009-09-14 18:39:43 +00004067 TPOC_Other)
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004068 != (*Best)->getPrimaryTemplate()) {
4069 Ambiguous = true;
4070 break;
4071 }
4072 }
4073
4074 // If one function template was more specialized than all of the
4075 // others, return it.
4076 if (!Ambiguous)
4077 return *Best;
4078
4079 // We could not find a most-specialized function template, which
4080 // is equivalent to having a set of function templates with more
4081 // than one such template. So, we place all of the function
4082 // templates into the set of remaining matches and produce a
4083 // diagnostic below. FIXME: we could perform the quadratic
4084 // algorithm here, pruning the result set to limit the number of
4085 // candidates output later.
Douglas Gregord173b202009-09-14 22:02:01 +00004086 RemainingMatches.append(Matches.begin(), Matches.end());
Douglas Gregor00aeb522009-07-08 23:33:52 +00004087 }
Mike Stump1eb44332009-09-09 15:08:12 +00004088
4089 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00004090 // selected function.
4091 if (RemainingMatches.size() == 1)
4092 return RemainingMatches.front();
Mike Stump1eb44332009-09-09 15:08:12 +00004093
Douglas Gregor00aeb522009-07-08 23:33:52 +00004094 // FIXME: We should probably return the same thing that BestViableFunction
4095 // returns (even if we issue the diagnostics here).
4096 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4097 << RemainingMatches[0]->getDeclName();
4098 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4099 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregor904eed32008-11-10 20:40:00 +00004100 return 0;
4101}
4102
Douglas Gregorf6b89692008-11-26 05:54:23 +00004103/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00004104/// (which eventually refers to the declaration Func) and the call
4105/// arguments Args/NumArgs, attempt to resolve the function call down
4106/// to a specific function. If overload resolution succeeds, returns
4107/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00004108/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00004109/// arguments and Fn, and returns NULL.
Douglas Gregorfa047642009-02-04 00:32:51 +00004110FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor17330012009-02-04 15:01:18 +00004111 DeclarationName UnqualifiedName,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004112 bool HasExplicitTemplateArgs,
4113 const TemplateArgument *ExplicitTemplateArgs,
4114 unsigned NumExplicitTemplateArgs,
Douglas Gregor0a396682008-11-26 06:01:48 +00004115 SourceLocation LParenLoc,
4116 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00004117 SourceLocation *CommaLocs,
Douglas Gregorfa047642009-02-04 00:32:51 +00004118 SourceLocation RParenLoc,
Douglas Gregor17330012009-02-04 15:01:18 +00004119 bool &ArgumentDependentLookup) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00004120 OverloadCandidateSet CandidateSet;
Douglas Gregor17330012009-02-04 15:01:18 +00004121
4122 // Add the functions denoted by Callee to the set of candidate
4123 // functions. While we're doing so, track whether argument-dependent
4124 // lookup still applies, per:
4125 //
4126 // C++0x [basic.lookup.argdep]p3:
4127 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4128 // and let Y be the lookup set produced by argument dependent
4129 // lookup (defined as follows). If X contains
4130 //
Mike Stump1eb44332009-09-09 15:08:12 +00004131 // -- a declaration of a class member, or
Douglas Gregor17330012009-02-04 15:01:18 +00004132 //
4133 // -- a block-scope function declaration that is not a
Mike Stump1eb44332009-09-09 15:08:12 +00004134 // using-declaration, or
4135 //
Douglas Gregor17330012009-02-04 15:01:18 +00004136 // -- a declaration that is neither a function or a function
4137 // template
4138 //
Mike Stump1eb44332009-09-09 15:08:12 +00004139 // then Y is empty.
4140 if (OverloadedFunctionDecl *Ovl
Douglas Gregor17330012009-02-04 15:01:18 +00004141 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
4142 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4143 FuncEnd = Ovl->function_end();
4144 Func != FuncEnd; ++Func) {
Douglas Gregore53060f2009-06-25 22:08:12 +00004145 DeclContext *Ctx = 0;
4146 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Func)) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004147 if (HasExplicitTemplateArgs)
4148 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00004149
Douglas Gregore53060f2009-06-25 22:08:12 +00004150 AddOverloadCandidate(FunDecl, Args, NumArgs, CandidateSet);
4151 Ctx = FunDecl->getDeclContext();
4152 } else {
4153 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*Func);
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004154 AddTemplateOverloadCandidate(FunTmpl, HasExplicitTemplateArgs,
4155 ExplicitTemplateArgs,
4156 NumExplicitTemplateArgs,
4157 Args, NumArgs, CandidateSet);
Douglas Gregore53060f2009-06-25 22:08:12 +00004158 Ctx = FunTmpl->getDeclContext();
4159 }
Douglas Gregor17330012009-02-04 15:01:18 +00004160
Douglas Gregore53060f2009-06-25 22:08:12 +00004161
4162 if (Ctx->isRecord() || Ctx->isFunctionOrMethod())
Douglas Gregor17330012009-02-04 15:01:18 +00004163 ArgumentDependentLookup = false;
4164 }
4165 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004166 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregor17330012009-02-04 15:01:18 +00004167 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
4168
4169 if (Func->getDeclContext()->isRecord() ||
4170 Func->getDeclContext()->isFunctionOrMethod())
4171 ArgumentDependentLookup = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004172 } else if (FunctionTemplateDecl *FuncTemplate
Douglas Gregore53060f2009-06-25 22:08:12 +00004173 = dyn_cast_or_null<FunctionTemplateDecl>(Callee)) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004174 AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4175 ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00004176 NumExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004177 Args, NumArgs, CandidateSet);
Douglas Gregore53060f2009-06-25 22:08:12 +00004178
4179 if (FuncTemplate->getDeclContext()->isRecord())
4180 ArgumentDependentLookup = false;
4181 }
Douglas Gregor17330012009-02-04 15:01:18 +00004182
4183 if (Callee)
4184 UnqualifiedName = Callee->getDeclName();
4185
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004186 // FIXME: Pass explicit template arguments through for ADL
Douglas Gregorfa047642009-02-04 00:32:51 +00004187 if (ArgumentDependentLookup)
Douglas Gregor17330012009-02-04 15:01:18 +00004188 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregorfa047642009-02-04 00:32:51 +00004189 CandidateSet);
4190
Douglas Gregorf6b89692008-11-26 05:54:23 +00004191 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004192 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00004193 case OR_Success:
4194 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00004195
4196 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00004197 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00004198 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00004199 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00004200 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4201 break;
4202
4203 case OR_Ambiguous:
4204 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor17330012009-02-04 15:01:18 +00004205 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00004206 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4207 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004208
4209 case OR_Deleted:
4210 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4211 << Best->Function->isDeleted()
4212 << UnqualifiedName
4213 << Fn->getSourceRange();
4214 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4215 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00004216 }
4217
4218 // Overload resolution failed. Destroy all of the subexpressions and
4219 // return NULL.
4220 Fn->Destroy(Context);
4221 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4222 Args[Arg]->Destroy(Context);
4223 return 0;
4224}
4225
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004226/// \brief Create a unary operation that may resolve to an overloaded
4227/// operator.
4228///
4229/// \param OpLoc The location of the operator itself (e.g., '*').
4230///
4231/// \param OpcIn The UnaryOperator::Opcode that describes this
4232/// operator.
4233///
4234/// \param Functions The set of non-member functions that will be
4235/// considered by overload resolution. The caller needs to build this
4236/// set based on the context using, e.g.,
4237/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4238/// set should not contain any member functions; those will be added
4239/// by CreateOverloadedUnaryOp().
4240///
4241/// \param input The input argument.
4242Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4243 unsigned OpcIn,
4244 FunctionSet &Functions,
Mike Stump1eb44332009-09-09 15:08:12 +00004245 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004246 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4247 Expr *Input = (Expr *)input.get();
4248
4249 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4250 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4251 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4252
4253 Expr *Args[2] = { Input, 0 };
4254 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004255
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004256 // For post-increment and post-decrement, add the implicit '0' as
4257 // the second argument, so that we know this is a post-increment or
4258 // post-decrement.
4259 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4260 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00004261 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004262 SourceLocation());
4263 NumArgs = 2;
4264 }
4265
4266 if (Input->isTypeDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004267 OverloadedFunctionDecl *Overloads
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004268 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump1eb44332009-09-09 15:08:12 +00004269 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004270 FuncEnd = Functions.end();
4271 Func != FuncEnd; ++Func)
4272 Overloads->addOverload(*Func);
4273
4274 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4275 OpLoc, false, false);
Mike Stump1eb44332009-09-09 15:08:12 +00004276
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004277 input.release();
4278 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4279 &Args[0], NumArgs,
4280 Context.DependentTy,
4281 OpLoc));
4282 }
4283
4284 // Build an empty overload set.
4285 OverloadCandidateSet CandidateSet;
4286
4287 // Add the candidates from the given function set.
4288 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4289
4290 // Add operator candidates that are member functions.
4291 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4292
4293 // Add builtin operator candidates.
4294 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4295
4296 // Perform overload resolution.
4297 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004298 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004299 case OR_Success: {
4300 // We found a built-in operator or an overloaded operator.
4301 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00004302
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004303 if (FnDecl) {
4304 // We matched an overloaded operator. Build a call to that
4305 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00004306
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004307 // Convert the arguments.
4308 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4309 if (PerformObjectArgumentInitialization(Input, Method))
4310 return ExprError();
4311 } else {
4312 // Convert the arguments.
4313 if (PerformCopyInitialization(Input,
4314 FnDecl->getParamDecl(0)->getType(),
4315 "passing"))
4316 return ExprError();
4317 }
4318
4319 // Determine the result type
4320 QualType ResultTy
4321 = FnDecl->getType()->getAsFunctionType()->getResultType();
4322 ResultTy = ResultTy.getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00004323
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004324 // Build the actual expression node.
4325 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4326 SourceLocation());
4327 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004328
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004329 input.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004330
4331 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlsson2d46eb22009-08-16 04:11:06 +00004332 &Input, 1, ResultTy, OpLoc);
4333 return MaybeBindToTemporary(CE);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004334 } else {
4335 // We matched a built-in operator. Convert the arguments, then
4336 // break out so that we will build the appropriate built-in
4337 // operator node.
4338 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4339 Best->Conversions[0], "passing"))
4340 return ExprError();
4341
4342 break;
4343 }
4344 }
4345
4346 case OR_No_Viable_Function:
4347 // No viable function; fall through to handling this as a
4348 // built-in operator, which will produce an error message for us.
4349 break;
4350
4351 case OR_Ambiguous:
4352 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4353 << UnaryOperator::getOpcodeStr(Opc)
4354 << Input->getSourceRange();
4355 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4356 return ExprError();
4357
4358 case OR_Deleted:
4359 Diag(OpLoc, diag::err_ovl_deleted_oper)
4360 << Best->Function->isDeleted()
4361 << UnaryOperator::getOpcodeStr(Opc)
4362 << Input->getSourceRange();
4363 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4364 return ExprError();
4365 }
4366
4367 // Either we found no viable overloaded operator or we matched a
4368 // built-in operator. In either case, fall through to trying to
4369 // build a built-in operation.
4370 input.release();
4371 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4372}
4373
Douglas Gregor063daf62009-03-13 18:40:31 +00004374/// \brief Create a binary operation that may resolve to an overloaded
4375/// operator.
4376///
4377/// \param OpLoc The location of the operator itself (e.g., '+').
4378///
4379/// \param OpcIn The BinaryOperator::Opcode that describes this
4380/// operator.
4381///
4382/// \param Functions The set of non-member functions that will be
4383/// considered by overload resolution. The caller needs to build this
4384/// set based on the context using, e.g.,
4385/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4386/// set should not contain any member functions; those will be added
4387/// by CreateOverloadedBinOp().
4388///
4389/// \param LHS Left-hand argument.
4390/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00004391Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00004392Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004393 unsigned OpcIn,
Douglas Gregor063daf62009-03-13 18:40:31 +00004394 FunctionSet &Functions,
4395 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00004396 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004397 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00004398
4399 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4400 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4401 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4402
4403 // If either side is type-dependent, create an appropriate dependent
4404 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004405 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor063daf62009-03-13 18:40:31 +00004406 // .* cannot be overloaded.
4407 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004408 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
Douglas Gregor063daf62009-03-13 18:40:31 +00004409 Context.DependentTy, OpLoc));
4410
Mike Stump1eb44332009-09-09 15:08:12 +00004411 OverloadedFunctionDecl *Overloads
Douglas Gregor063daf62009-03-13 18:40:31 +00004412 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump1eb44332009-09-09 15:08:12 +00004413 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004414 FuncEnd = Functions.end();
4415 Func != FuncEnd; ++Func)
4416 Overloads->addOverload(*Func);
4417
4418 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4419 OpLoc, false, false);
Mike Stump1eb44332009-09-09 15:08:12 +00004420
Douglas Gregor063daf62009-03-13 18:40:31 +00004421 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00004422 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00004423 Context.DependentTy,
4424 OpLoc));
4425 }
4426
4427 // If this is the .* operator, which is not overloadable, just
4428 // create a built-in binary operator.
4429 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004430 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00004431
4432 // If this is one of the assignment operators, we only perform
4433 // overload resolution if the left-hand side is a class or
4434 // enumeration type (C++ [expr.ass]p3).
4435 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004436 !Args[0]->getType()->isOverloadableType())
4437 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00004438
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004439 // Build an empty overload set.
4440 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00004441
4442 // Add the candidates from the given function set.
4443 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4444
4445 // Add operator candidates that are member functions.
4446 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4447
4448 // Add builtin operator candidates.
4449 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4450
4451 // Perform overload resolution.
4452 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004453 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004454 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00004455 // We found a built-in operator or an overloaded operator.
4456 FunctionDecl *FnDecl = Best->Function;
4457
4458 if (FnDecl) {
4459 // We matched an overloaded operator. Build a call to that
4460 // operator.
4461
4462 // Convert the arguments.
4463 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004464 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4465 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004466 "passing"))
4467 return ExprError();
4468 } else {
4469 // Convert the arguments.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004470 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004471 "passing") ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004472 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004473 "passing"))
4474 return ExprError();
4475 }
4476
4477 // Determine the result type
4478 QualType ResultTy
4479 = FnDecl->getType()->getAsFunctionType()->getResultType();
4480 ResultTy = ResultTy.getNonReferenceType();
4481
4482 // Build the actual expression node.
4483 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00004484 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00004485 UsualUnaryConversions(FnExpr);
4486
Mike Stump1eb44332009-09-09 15:08:12 +00004487 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlsson2d46eb22009-08-16 04:11:06 +00004488 Args, 2, ResultTy, OpLoc);
4489 return MaybeBindToTemporary(CE);
Douglas Gregor063daf62009-03-13 18:40:31 +00004490 } else {
4491 // We matched a built-in operator. Convert the arguments, then
4492 // break out so that we will build the appropriate built-in
4493 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004494 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor063daf62009-03-13 18:40:31 +00004495 Best->Conversions[0], "passing") ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004496 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor063daf62009-03-13 18:40:31 +00004497 Best->Conversions[1], "passing"))
4498 return ExprError();
4499
4500 break;
4501 }
4502 }
4503
4504 case OR_No_Viable_Function:
Sebastian Redl8593c782009-05-21 11:50:50 +00004505 // For class as left operand for assignment or compound assigment operator
4506 // do not fall through to handling in built-in, but report that no overloaded
4507 // assignment operator found
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004508 if (Args[0]->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00004509 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4510 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004511 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Sebastian Redl8593c782009-05-21 11:50:50 +00004512 return ExprError();
4513 }
Douglas Gregor063daf62009-03-13 18:40:31 +00004514 // No viable function; fall through to handling this as a
4515 // built-in operator, which will produce an error message for us.
4516 break;
4517
4518 case OR_Ambiguous:
4519 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4520 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004521 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor063daf62009-03-13 18:40:31 +00004522 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4523 return ExprError();
4524
4525 case OR_Deleted:
4526 Diag(OpLoc, diag::err_ovl_deleted_oper)
4527 << Best->Function->isDeleted()
4528 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004529 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor063daf62009-03-13 18:40:31 +00004530 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4531 return ExprError();
4532 }
4533
4534 // Either we found no viable overloaded operator or we matched a
4535 // built-in operator. In either case, try to build a built-in
4536 // operation.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004537 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00004538}
4539
Douglas Gregor88a35142008-12-22 05:46:06 +00004540/// BuildCallToMemberFunction - Build a call to a member
4541/// function. MemExpr is the expression that refers to the member
4542/// function (and includes the object parameter), Args/NumArgs are the
4543/// arguments to the function call (not including the object
4544/// parameter). The caller needs to validate that the member
4545/// expression refers to a member function or an overloaded member
4546/// function.
4547Sema::ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00004548Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4549 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00004550 unsigned NumArgs, SourceLocation *CommaLocs,
4551 SourceLocation RParenLoc) {
4552 // Dig out the member expression. This holds both the object
4553 // argument and the member function we're referring to.
4554 MemberExpr *MemExpr = 0;
4555 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4556 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4557 else
4558 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4559 assert(MemExpr && "Building member call without member expression");
4560
4561 // Extract the object argument.
4562 Expr *ObjectArg = MemExpr->getBase();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004563
Douglas Gregor88a35142008-12-22 05:46:06 +00004564 CXXMethodDecl *Method = 0;
Douglas Gregor6b906862009-08-21 00:16:32 +00004565 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4566 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004567 // Add overload candidates
4568 OverloadCandidateSet CandidateSet;
Douglas Gregor6b906862009-08-21 00:16:32 +00004569 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00004570
Douglas Gregordec06662009-08-21 18:42:58 +00004571 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4572 Func != FuncEnd; ++Func) {
4573 if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
Mike Stump1eb44332009-09-09 15:08:12 +00004574 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +00004575 /*SuppressUserConversions=*/false);
4576 else
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00004577 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4578 MemExpr->hasExplicitTemplateArgumentList(),
4579 MemExpr->getTemplateArgs(),
4580 MemExpr->getNumTemplateArgs(),
4581 ObjectArg, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00004582 CandidateSet,
4583 /*SuppressUsedConversions=*/false);
4584 }
Mike Stump1eb44332009-09-09 15:08:12 +00004585
Douglas Gregor88a35142008-12-22 05:46:06 +00004586 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004587 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004588 case OR_Success:
4589 Method = cast<CXXMethodDecl>(Best->Function);
4590 break;
4591
4592 case OR_No_Viable_Function:
Mike Stump1eb44332009-09-09 15:08:12 +00004593 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor88a35142008-12-22 05:46:06 +00004594 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00004595 << DeclName << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00004596 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4597 // FIXME: Leaking incoming expressions!
4598 return true;
4599
4600 case OR_Ambiguous:
Mike Stump1eb44332009-09-09 15:08:12 +00004601 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor88a35142008-12-22 05:46:06 +00004602 diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00004603 << DeclName << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00004604 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4605 // FIXME: Leaking incoming expressions!
4606 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004607
4608 case OR_Deleted:
Mike Stump1eb44332009-09-09 15:08:12 +00004609 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004610 diag::err_ovl_deleted_member_call)
4611 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00004612 << DeclName << MemExprE->getSourceRange();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004613 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4614 // FIXME: Leaking incoming expressions!
4615 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004616 }
4617
4618 FixOverloadedFunctionReference(MemExpr, Method);
4619 } else {
4620 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4621 }
4622
4623 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00004624 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek668bf912009-02-09 20:51:47 +00004625 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00004626 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00004627 Method->getResultType().getNonReferenceType(),
4628 RParenLoc));
4629
4630 // Convert the object argument (for a non-static member function call).
Mike Stump1eb44332009-09-09 15:08:12 +00004631 if (!Method->isStatic() &&
Douglas Gregor88a35142008-12-22 05:46:06 +00004632 PerformObjectArgumentInitialization(ObjectArg, Method))
4633 return true;
4634 MemExpr->setBase(ObjectArg);
4635
4636 // Convert the rest of the arguments
Douglas Gregor72564e72009-02-26 23:50:07 +00004637 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004638 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00004639 RParenLoc))
4640 return true;
4641
Anders Carlssond406bf02009-08-16 01:56:34 +00004642 if (CheckFunctionCall(Method, TheCall.get()))
4643 return true;
Anders Carlsson6f680272009-08-16 03:42:12 +00004644
4645 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor88a35142008-12-22 05:46:06 +00004646}
4647
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004648/// BuildCallToObjectOfClassType - Build a call to an object of class
4649/// type (C++ [over.call.object]), which can end up invoking an
4650/// overloaded function call operator (@c operator()) or performing a
4651/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00004652Sema::ExprResult
4653Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00004654 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004655 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00004656 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004657 SourceLocation RParenLoc) {
4658 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00004659 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004660
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004661 // C++ [over.call.object]p1:
4662 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00004663 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004664 // candidate functions includes at least the function call
4665 // operators of T. The function call operators of T are obtained by
4666 // ordinary lookup of the name operator() in the context of
4667 // (E).operator().
4668 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00004669 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004670 DeclContext::lookup_const_iterator Oper, OperEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004671 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004672 Oper != OperEnd; ++Oper)
Mike Stump1eb44332009-09-09 15:08:12 +00004673 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004674 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004675
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004676 // C++ [over.call.object]p2:
4677 // In addition, for each conversion function declared in T of the
4678 // form
4679 //
4680 // operator conversion-type-id () cv-qualifier;
4681 //
4682 // where cv-qualifier is the same cv-qualification as, or a
4683 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00004684 // denotes the type "pointer to function of (P1,...,Pn) returning
4685 // R", or the type "reference to pointer to function of
4686 // (P1,...,Pn) returning R", or the type "reference to function
4687 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004688 // is also considered as a candidate function. Similarly,
4689 // surrogate call functions are added to the set of candidate
4690 // functions for each conversion function declared in an
4691 // accessible base class provided the function is not hidden
4692 // within T by another intervening declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00004693
Douglas Gregor5842ba92009-08-24 15:23:48 +00004694 if (!RequireCompleteType(SourceLocation(), Object->getType(), 0)) {
4695 // FIXME: Look in base classes for more conversion operators!
Mike Stump1eb44332009-09-09 15:08:12 +00004696 OverloadedFunctionDecl *Conversions
Douglas Gregor5842ba92009-08-24 15:23:48 +00004697 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00004698 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor5842ba92009-08-24 15:23:48 +00004699 Func = Conversions->function_begin(),
4700 FuncEnd = Conversions->function_end();
4701 Func != FuncEnd; ++Func) {
4702 CXXConversionDecl *Conv;
4703 FunctionTemplateDecl *ConvTemplate;
4704 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004705
Douglas Gregor5842ba92009-08-24 15:23:48 +00004706 // Skip over templated conversion functions; they aren't
4707 // surrogates.
4708 if (ConvTemplate)
4709 continue;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004710
Douglas Gregor5842ba92009-08-24 15:23:48 +00004711 // Strip the reference type (if any) and then the pointer type (if
4712 // any) to get down to what might be a function type.
4713 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4714 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4715 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004716
Douglas Gregor5842ba92009-08-24 15:23:48 +00004717 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
4718 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4719 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004720 }
Mike Stump1eb44332009-09-09 15:08:12 +00004721
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004722 // Perform overload resolution.
4723 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004724 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004725 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004726 // Overload resolution succeeded; we'll build the appropriate call
4727 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004728 break;
4729
4730 case OR_No_Viable_Function:
Mike Stump1eb44332009-09-09 15:08:12 +00004731 Diag(Object->getSourceRange().getBegin(),
Sebastian Redle4c452c2008-11-22 13:44:36 +00004732 diag::err_ovl_no_viable_object_call)
Chris Lattner4330d652009-02-17 07:29:20 +00004733 << Object->getType() << Object->getSourceRange();
Sebastian Redle4c452c2008-11-22 13:44:36 +00004734 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004735 break;
4736
4737 case OR_Ambiguous:
4738 Diag(Object->getSourceRange().getBegin(),
4739 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00004740 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004741 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4742 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004743
4744 case OR_Deleted:
4745 Diag(Object->getSourceRange().getBegin(),
4746 diag::err_ovl_deleted_object_call)
4747 << Best->Function->isDeleted()
4748 << Object->getType() << Object->getSourceRange();
4749 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4750 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004751 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004752
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004753 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004754 // We had an error; delete all of the subexpressions and return
4755 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004756 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004757 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00004758 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004759 return true;
4760 }
4761
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004762 if (Best->Function == 0) {
4763 // Since there is no function declaration, this is one of the
4764 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00004765 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004766 = cast<CXXConversionDecl>(
4767 Best->Conversions[0].UserDefined.ConversionFunction);
4768
4769 // We selected one of the surrogate functions that converts the
4770 // object parameter to a function pointer. Perform the conversion
4771 // on the object argument, then let ActOnCallExpr finish the job.
4772 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl0eb23302009-01-19 00:08:26 +00004773 ImpCastExprToType(Object,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004774 Conv->getConversionType().getNonReferenceType(),
Anders Carlsson3503d042009-07-31 01:23:52 +00004775 CastExpr::CK_Unknown,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004776 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00004777 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4778 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4779 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004780 }
4781
4782 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4783 // that calls this method, using Object for the implicit object
4784 // parameter and passing along the remaining arguments.
4785 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor72564e72009-02-26 23:50:07 +00004786 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004787
4788 unsigned NumArgsInProto = Proto->getNumArgs();
4789 unsigned NumArgsToCheck = NumArgs;
4790
4791 // Build the full argument list for the method call (the
4792 // implicit object parameter is placed at the beginning of the
4793 // list).
4794 Expr **MethodArgs;
4795 if (NumArgs < NumArgsInProto) {
4796 NumArgsToCheck = NumArgsInProto;
4797 MethodArgs = new Expr*[NumArgsInProto + 1];
4798 } else {
4799 MethodArgs = new Expr*[NumArgs + 1];
4800 }
4801 MethodArgs[0] = Object;
4802 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4803 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00004804
4805 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004806 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004807 UsualUnaryConversions(NewFn);
4808
4809 // Once we've built TheCall, all of the expressions are properly
4810 // owned.
4811 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00004812 ExprOwningPtr<CXXOperatorCallExpr>
4813 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00004814 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004815 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004816 delete [] MethodArgs;
4817
Douglas Gregor518fda12009-01-13 05:10:00 +00004818 // We may have default arguments. If so, we need to allocate more
4819 // slots in the call for them.
4820 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00004821 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00004822 else if (NumArgs > NumArgsInProto)
4823 NumArgsToCheck = NumArgsInProto;
4824
Chris Lattner312531a2009-04-12 08:11:20 +00004825 bool IsError = false;
4826
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004827 // Initialize the implicit object parameter.
Chris Lattner312531a2009-04-12 08:11:20 +00004828 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004829 TheCall->setArg(0, Object);
4830
Chris Lattner312531a2009-04-12 08:11:20 +00004831
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004832 // Check the argument types.
4833 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004834 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00004835 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004836 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00004837
Douglas Gregor518fda12009-01-13 05:10:00 +00004838 // Pass the argument.
4839 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner312531a2009-04-12 08:11:20 +00004840 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor518fda12009-01-13 05:10:00 +00004841 } else {
Anders Carlssonf1480ee2009-08-14 18:30:22 +00004842 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregor518fda12009-01-13 05:10:00 +00004843 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004844
4845 TheCall->setArg(i + 1, Arg);
4846 }
4847
4848 // If this is a variadic call, handle args passed through "...".
4849 if (Proto->isVariadic()) {
4850 // Promote the arguments (C99 6.5.2.2p7).
4851 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4852 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00004853 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004854 TheCall->setArg(i + 1, Arg);
4855 }
4856 }
4857
Chris Lattner312531a2009-04-12 08:11:20 +00004858 if (IsError) return true;
4859
Anders Carlssond406bf02009-08-16 01:56:34 +00004860 if (CheckFunctionCall(Method, TheCall.get()))
4861 return true;
4862
Anders Carlssona303f9e2009-08-16 03:53:54 +00004863 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004864}
4865
Douglas Gregor8ba10742008-11-20 16:27:02 +00004866/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00004867/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00004868/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004869Sema::OwningExprResult
4870Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
4871 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00004872 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00004873
Douglas Gregor8ba10742008-11-20 16:27:02 +00004874 // C++ [over.ref]p1:
4875 //
4876 // [...] An expression x->m is interpreted as (x.operator->())->m
4877 // for a class object x of type T if T::operator->() exists and if
4878 // the operator is selected as the best match function by the
4879 // overload resolution mechanism (13.3).
4880 // FIXME: look in base classes.
4881 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4882 OverloadCandidateSet CandidateSet;
Ted Kremenek6217b802009-07-29 21:53:49 +00004883 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004884
Anders Carlssone30572a2009-09-10 23:18:36 +00004885 LookupResult R = LookupQualifiedName(BaseRecord->getDecl(), OpName,
4886 LookupOrdinaryName);
4887
4888 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
4889 Oper != OperEnd; ++Oper)
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004890 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00004891 /*SuppressUserConversions=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00004892
4893 // Perform overload resolution.
4894 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004895 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00004896 case OR_Success:
4897 // Overload resolution succeeded; we'll build the call below.
4898 break;
4899
4900 case OR_No_Viable_Function:
4901 if (CandidateSet.empty())
4902 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004903 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004904 else
4905 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004906 << "operator->" << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004907 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004908 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004909
4910 case OR_Ambiguous:
4911 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00004912 << "->" << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004913 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004914 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004915
4916 case OR_Deleted:
4917 Diag(OpLoc, diag::err_ovl_deleted_oper)
4918 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00004919 << "->" << Base->getSourceRange();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004920 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004921 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004922 }
4923
4924 // Convert the object parameter.
4925 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00004926 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004927 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00004928
4929 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004930 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004931
4932 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004933 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4934 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00004935 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004936 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor8ba10742008-11-20 16:27:02 +00004937 Method->getResultType().getNonReferenceType(),
4938 OpLoc);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004939 return Owned(Base);
Douglas Gregor8ba10742008-11-20 16:27:02 +00004940}
4941
Douglas Gregor904eed32008-11-10 20:40:00 +00004942/// FixOverloadedFunctionReference - E is an expression that refers to
4943/// a C++ overloaded function (possibly with some parentheses and
4944/// perhaps a '&' around it). We have resolved the overloaded function
4945/// to the function declaration Fn, so patch up the expression E to
4946/// refer (possibly indirectly) to Fn.
4947void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4948 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4949 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4950 E->setType(PE->getSubExpr()->getType());
4951 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004952 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00004953 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00004954 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4955 if (Method->isStatic()) {
4956 // Do nothing: static member functions aren't any different
4957 // from non-member functions.
Mike Stump1eb44332009-09-09 15:08:12 +00004958 } else if (QualifiedDeclRefExpr *DRE
Douglas Gregorb86b0572009-02-11 01:18:59 +00004959 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4960 // We have taken the address of a pointer to member
4961 // function. Perform the computation here so that we get the
4962 // appropriate pointer to member type.
4963 DRE->setDecl(Fn);
4964 DRE->setType(Fn->getType());
4965 QualType ClassType
4966 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
Mike Stump1eb44332009-09-09 15:08:12 +00004967 E->setType(Context.getMemberPointerType(Fn->getType(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00004968 ClassType.getTypePtr()));
4969 return;
4970 }
4971 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004972 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregora35284b2009-02-11 00:19:33 +00004973 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor904eed32008-11-10 20:40:00 +00004974 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00004975 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004976 isa<FunctionTemplateDecl>(DR->getDecl())) &&
Douglas Gregor83314aa2009-07-08 20:55:45 +00004977 "Expected overloaded function or function template");
Douglas Gregor904eed32008-11-10 20:40:00 +00004978 DR->setDecl(Fn);
4979 E->setType(Fn->getType());
Douglas Gregor88a35142008-12-22 05:46:06 +00004980 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4981 MemExpr->setMemberDecl(Fn);
4982 E->setType(Fn->getType());
Douglas Gregor904eed32008-11-10 20:40:00 +00004983 } else {
4984 assert(false && "Invalid reference to overloaded function");
4985 }
4986}
4987
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004988} // end namespace clang