blob: 6c23a844bff811f0cfe9bb18a3d060c532d43fe9 [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;
Anders Carlsson08972922009-08-28 15:33:32 +0000413 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor60d62c22008-10-31 16:23:19 +0000414 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000415 else if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +0000416 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Sebastian Redle2b68332009-04-12 17:16:29 +0000417 !SuppressUserConversions, AllowExplicit,
418 ForceRValue)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000419 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000420 // C++ [over.ics.user]p4:
421 // A conversion of an expression of class type to the same class
422 // type is given Exact Match rank, and a conversion of an
423 // expression of class type to a base class of that type is
424 // given Conversion rank, in spite of the fact that a copy
425 // constructor (i.e., a user-defined conversion function) is
426 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000427 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000428 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000429 QualType FromCanon
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000430 = Context.getCanonicalType(From->getType().getUnqualifiedType());
431 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
432 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000433 // Turn this into a "standard" conversion sequence, so that it
434 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000435 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
436 ICS.Standard.setAsIdentityConversion();
437 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
438 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000439 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000440 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000441 ICS.Standard.Second = ICK_Derived_To_Base;
442 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000443 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000444
445 // C++ [over.best.ics]p4:
446 // However, when considering the argument of a user-defined
447 // conversion function that is a candidate by 13.3.1.3 when
448 // invoked for the copying of the temporary in the second step
449 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
450 // 13.3.1.6 in all cases, only standard conversion sequences and
451 // ellipsis conversion sequences are allowed.
452 if (SuppressUserConversions &&
453 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
454 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000455 } else
Douglas Gregor60d62c22008-10-31 16:23:19 +0000456 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000457
458 return ICS;
459}
460
461/// IsStandardConversion - Determines whether there is a standard
462/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
463/// expression From to the type ToType. Standard conversion sequences
464/// only consider non-class types; for conversions that involve class
465/// types, use TryImplicitConversion. If a conversion exists, SCS will
466/// contain the standard conversion sequence required to perform this
467/// conversion and this routine will return true. Otherwise, this
468/// routine will return false and the value of SCS is unspecified.
Mike Stump1eb44332009-09-09 15:08:12 +0000469bool
470Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000471 bool InOverloadResolution,
Mike Stump1eb44332009-09-09 15:08:12 +0000472 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000473 QualType FromType = From->getType();
474
Douglas Gregor60d62c22008-10-31 16:23:19 +0000475 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000476 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000477 SCS.Deprecated = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000478 SCS.IncompatibleObjC = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000479 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000480 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000481
Douglas Gregorf9201e02009-02-11 23:02:49 +0000482 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000483 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000484 if (FromType->isRecordType() || ToType->isRecordType()) {
485 if (getLangOptions().CPlusPlus)
486 return false;
487
Mike Stump1eb44332009-09-09 15:08:12 +0000488 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000489 }
490
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000491 // The first conversion can be an lvalue-to-rvalue conversion,
492 // array-to-pointer conversion, or function-to-pointer conversion
493 // (C++ 4p1).
494
Mike Stump1eb44332009-09-09 15:08:12 +0000495 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000496 // An lvalue (3.10) of a non-function, non-array type T can be
497 // converted to an rvalue.
498 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000499 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000500 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000501 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000502 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000503
504 // If T is a non-class type, the type of the rvalue is the
505 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000506 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
507 // just strip the qualifiers because they don't matter.
508
509 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregor60d62c22008-10-31 16:23:19 +0000510 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000511 } else if (FromType->isArrayType()) {
512 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000513 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000514
515 // An lvalue or rvalue of type "array of N T" or "array of unknown
516 // bound of T" can be converted to an rvalue of type "pointer to
517 // T" (C++ 4.2p1).
518 FromType = Context.getArrayDecayedType(FromType);
519
520 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
521 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000522 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000523
524 // For the purpose of ranking in overload resolution
525 // (13.3.3.1.1), this conversion is considered an
526 // array-to-pointer conversion followed by a qualification
527 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000528 SCS.Second = ICK_Identity;
529 SCS.Third = ICK_Qualification;
530 SCS.ToTypePtr = ToType.getAsOpaquePtr();
531 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000532 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000533 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
534 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000535 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000536
537 // An lvalue of function type T can be converted to an rvalue of
538 // type "pointer to T." The result is a pointer to the
539 // function. (C++ 4.3p1).
540 FromType = Context.getPointerType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000541 } else if (FunctionDecl *Fn
Douglas Gregor904eed32008-11-10 20:40:00 +0000542 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000543 // Address of overloaded function (C++ [over.over]).
Douglas Gregor904eed32008-11-10 20:40:00 +0000544 SCS.First = ICK_Function_To_Pointer;
545
546 // We were able to resolve the address of the overloaded function,
547 // so we can convert to the type of that function.
548 FromType = Fn->getType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000549 if (ToType->isLValueReferenceType())
550 FromType = Context.getLValueReferenceType(FromType);
551 else if (ToType->isRValueReferenceType())
552 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000553 else if (ToType->isMemberPointerType()) {
554 // Resolve address only succeeds if both sides are member pointers,
555 // but it doesn't have to be the same class. See DR 247.
556 // Note that this means that the type of &Derived::fn can be
557 // Ret (Base::*)(Args) if the fn overload actually found is from the
558 // base class, even if it was brought into the derived class via a
559 // using declaration. The standard isn't clear on this issue at all.
560 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
561 FromType = Context.getMemberPointerType(FromType,
562 Context.getTypeDeclType(M->getParent()).getTypePtr());
563 } else
Douglas Gregor904eed32008-11-10 20:40:00 +0000564 FromType = Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000565 } else {
566 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000567 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000568 }
569
570 // The second conversion can be an integral promotion, floating
571 // point promotion, integral conversion, floating point conversion,
572 // floating-integral conversion, pointer conversion,
573 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000574 // For overloading in C, this can also be a "compatible-type"
575 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000576 bool IncompatibleObjC = false;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000577 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000578 // The unqualified versions of the types are the same: there's no
579 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000580 SCS.Second = ICK_Identity;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000581 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000582 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000583 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000584 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000585 } else if (IsFloatingPointPromotion(FromType, ToType)) {
586 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000587 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000588 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000589 } else if (IsComplexPromotion(FromType, ToType)) {
590 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000591 SCS.Second = ICK_Complex_Promotion;
592 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000593 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000594 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000595 // Integral conversions (C++ 4.7).
596 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000597 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000598 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000599 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
600 // Floating point conversions (C++ 4.8).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000601 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000602 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000603 } else if (FromType->isComplexType() && ToType->isComplexType()) {
604 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000605 SCS.Second = ICK_Complex_Conversion;
606 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000607 } else if ((FromType->isFloatingType() &&
608 ToType->isIntegralType() && (!ToType->isBooleanType() &&
609 !ToType->isEnumeralType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000610 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000611 ToType->isFloatingType())) {
612 // Floating-integral conversions (C++ 4.9).
613 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000614 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000615 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000616 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
617 (ToType->isComplexType() && FromType->isArithmeticType())) {
618 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000619 SCS.Second = ICK_Complex_Real;
620 FromType = ToType.getUnqualifiedType();
Anders Carlsson08972922009-08-28 15:33:32 +0000621 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
622 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000623 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000624 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000625 SCS.IncompatibleObjC = IncompatibleObjC;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000626 } else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
627 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000628 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000629 } else if (ToType->isBooleanType() &&
630 (FromType->isArithmeticType() ||
631 FromType->isEnumeralType() ||
632 FromType->isPointerType() ||
633 FromType->isBlockPointerType() ||
634 FromType->isMemberPointerType() ||
635 FromType->isNullPtrType())) {
636 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000637 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000638 FromType = Context.BoolTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000639 } else if (!getLangOptions().CPlusPlus &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000640 Context.typesAreCompatible(ToType, FromType)) {
641 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000642 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000643 } else {
644 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000645 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000646 }
647
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000648 QualType CanonFrom;
649 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000650 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000651 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000652 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000653 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000654 CanonFrom = Context.getCanonicalType(FromType);
655 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000656 } else {
657 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000658 SCS.Third = ICK_Identity;
659
Mike Stump1eb44332009-09-09 15:08:12 +0000660 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +0000661 // [...] Any difference in top-level cv-qualification is
662 // subsumed by the initialization itself and does not constitute
663 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000664 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000665 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000666 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000667 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
668 FromType = ToType;
669 CanonFrom = CanonTo;
670 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000671 }
672
673 // If we have not converted the argument type to the parameter type,
674 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000675 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000676 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000677
Douglas Gregor60d62c22008-10-31 16:23:19 +0000678 SCS.ToTypePtr = FromType.getAsOpaquePtr();
679 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000680}
681
682/// IsIntegralPromotion - Determines whether the conversion from the
683/// expression From (whose potentially-adjusted type is FromType) to
684/// ToType is an integral promotion (C++ 4.5). If so, returns true and
685/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000686bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000687 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000688 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000689 if (!To) {
690 return false;
691 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000692
693 // An rvalue of type char, signed char, unsigned char, short int, or
694 // unsigned short int can be converted to an rvalue of type int if
695 // int can represent all the values of the source type; otherwise,
696 // the source rvalue can be converted to an rvalue of type unsigned
697 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000698 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000699 if (// We can promote any signed, promotable integer type to an int
700 (FromType->isSignedIntegerType() ||
701 // We can promote any unsigned integer type whose size is
702 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +0000703 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000704 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000705 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000706 }
707
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000708 return To->getKind() == BuiltinType::UInt;
709 }
710
711 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
712 // can be converted to an rvalue of the first of the following types
713 // that can represent all the values of its underlying type: int,
714 // unsigned int, long, or unsigned long (C++ 4.5p2).
715 if ((FromType->isEnumeralType() || FromType->isWideCharType())
716 && ToType->isIntegerType()) {
717 // Determine whether the type we're converting from is signed or
718 // unsigned.
719 bool FromIsSigned;
720 uint64_t FromSize = Context.getTypeSize(FromType);
721 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
722 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
723 FromIsSigned = UnderlyingType->isSignedIntegerType();
724 } else {
725 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
726 FromIsSigned = true;
727 }
728
729 // The types we'll try to promote to, in the appropriate
730 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +0000731 QualType PromoteTypes[6] = {
732 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000733 Context.LongTy, Context.UnsignedLongTy ,
734 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000735 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000736 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000737 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
738 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +0000739 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000740 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
741 // We found the type that we can promote to. If this is the
742 // type we wanted, we have a promotion. Otherwise, no
743 // promotion.
Sebastian Redl07779722008-10-31 14:43:28 +0000744 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000745 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
746 }
747 }
748 }
749
750 // An rvalue for an integral bit-field (9.6) can be converted to an
751 // rvalue of type int if int can represent all the values of the
752 // bit-field; otherwise, it can be converted to unsigned int if
753 // unsigned int can represent all the values of the bit-field. If
754 // the bit-field is larger yet, no integral promotion applies to
755 // it. If the bit-field has an enumerated type, it is treated as any
756 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +0000757 // FIXME: We should delay checking of bit-fields until we actually perform the
758 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000759 using llvm::APSInt;
760 if (From)
761 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +0000762 APSInt BitWidth;
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000763 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
764 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
765 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
766 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Douglas Gregor86f19402008-12-20 23:49:58 +0000768 // Are we promoting to an int from a bitfield that fits in an int?
769 if (BitWidth < ToSize ||
770 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
771 return To->getKind() == BuiltinType::Int;
772 }
Mike Stump1eb44332009-09-09 15:08:12 +0000773
Douglas Gregor86f19402008-12-20 23:49:58 +0000774 // Are we promoting to an unsigned int from an unsigned bitfield
775 // that fits into an unsigned int?
776 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
777 return To->getKind() == BuiltinType::UInt;
778 }
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Douglas Gregor86f19402008-12-20 23:49:58 +0000780 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000781 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000782 }
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000784 // An rvalue of type bool can be converted to an rvalue of type int,
785 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000786 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000787 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000788 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000789
790 return false;
791}
792
793/// IsFloatingPointPromotion - Determines whether the conversion from
794/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
795/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000796bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000797 /// An rvalue of type float can be converted to an rvalue of type
798 /// double. (C++ 4.6p1).
799 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000800 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000801 if (FromBuiltin->getKind() == BuiltinType::Float &&
802 ToBuiltin->getKind() == BuiltinType::Double)
803 return true;
804
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000805 // C99 6.3.1.5p1:
806 // When a float is promoted to double or long double, or a
807 // double is promoted to long double [...].
808 if (!getLangOptions().CPlusPlus &&
809 (FromBuiltin->getKind() == BuiltinType::Float ||
810 FromBuiltin->getKind() == BuiltinType::Double) &&
811 (ToBuiltin->getKind() == BuiltinType::LongDouble))
812 return true;
813 }
814
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000815 return false;
816}
817
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000818/// \brief Determine if a conversion is a complex promotion.
819///
820/// A complex promotion is defined as a complex -> complex conversion
821/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000822/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000823bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
824 const ComplexType *FromComplex = FromType->getAsComplexType();
825 if (!FromComplex)
826 return false;
827
828 const ComplexType *ToComplex = ToType->getAsComplexType();
829 if (!ToComplex)
830 return false;
831
832 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000833 ToComplex->getElementType()) ||
834 IsIntegralPromotion(0, FromComplex->getElementType(),
835 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000836}
837
Douglas Gregorcb7de522008-11-26 23:31:11 +0000838/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
839/// the pointer type FromPtr to a pointer to type ToPointee, with the
840/// same type qualifiers as FromPtr has on its pointee type. ToType,
841/// if non-empty, will be a pointer to ToType that may or may not have
842/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +0000843static QualType
844BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000845 QualType ToPointee, QualType ToType,
846 ASTContext &Context) {
847 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
848 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
849 unsigned Quals = CanonFromPointee.getCVRQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +0000850
851 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregorcb7de522008-11-26 23:31:11 +0000852 if (CanonToPointee.getCVRQualifiers() == Quals) {
853 // ToType is exactly what we need. Return it.
854 if (ToType.getTypePtr())
855 return ToType;
856
857 // Build a pointer to ToPointee. It has the right qualifiers
858 // already.
859 return Context.getPointerType(ToPointee);
860 }
861
862 // Just build a canonical type that has the right qualifiers.
863 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
864}
865
Mike Stump1eb44332009-09-09 15:08:12 +0000866static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000867 bool InOverloadResolution,
868 ASTContext &Context) {
869 // Handle value-dependent integral null pointer constants correctly.
870 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
871 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
872 Expr->getType()->isIntegralType())
873 return !InOverloadResolution;
874
875 return Expr->isNullPointerConstant(Context);
876}
Mike Stump1eb44332009-09-09 15:08:12 +0000877
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000878/// IsPointerConversion - Determines whether the conversion of the
879/// expression From, which has the (possibly adjusted) type FromType,
880/// can be converted to the type ToType via a pointer conversion (C++
881/// 4.10). If so, returns true and places the converted type (that
882/// might differ from ToType in its cv-qualifiers at some level) into
883/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000884///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000885/// This routine also supports conversions to and from block pointers
886/// and conversions with Objective-C's 'id', 'id<protocols...>', and
887/// pointers to interfaces. FIXME: Once we've determined the
888/// appropriate overloading rules for Objective-C, we may want to
889/// split the Objective-C checks into a different routine; however,
890/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000891/// conversions, so for now they live here. IncompatibleObjC will be
892/// set if the conversion is an allowed Objective-C conversion that
893/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000894bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000895 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +0000896 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +0000897 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +0000898 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000899 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
900 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000901
Mike Stump1eb44332009-09-09 15:08:12 +0000902 // Conversion from a null pointer constant to any Objective-C pointer type.
903 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000904 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +0000905 ConvertedType = ToType;
906 return true;
907 }
908
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000909 // Blocks: Block pointers can be converted to void*.
910 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000911 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000912 ConvertedType = ToType;
913 return true;
914 }
915 // Blocks: A null pointer constant can be converted to a block
916 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +0000917 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000918 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000919 ConvertedType = ToType;
920 return true;
921 }
922
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000923 // If the left-hand-side is nullptr_t, the right side can be a null
924 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +0000925 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000926 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000927 ConvertedType = ToType;
928 return true;
929 }
930
Ted Kremenek6217b802009-07-29 21:53:49 +0000931 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000932 if (!ToTypePtr)
933 return false;
934
935 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000936 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000937 ConvertedType = ToType;
938 return true;
939 }
Sebastian Redl07779722008-10-31 14:43:28 +0000940
Douglas Gregorcb7de522008-11-26 23:31:11 +0000941 // Beyond this point, both types need to be pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +0000942 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +0000943 if (!FromTypePtr)
944 return false;
945
946 QualType FromPointeeType = FromTypePtr->getPointeeType();
947 QualType ToPointeeType = ToTypePtr->getPointeeType();
948
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000949 // An rvalue of type "pointer to cv T," where T is an object type,
950 // can be converted to an rvalue of type "pointer to cv void" (C++
951 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +0000952 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000953 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +0000954 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000955 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000956 return true;
957 }
958
Douglas Gregorf9201e02009-02-11 23:02:49 +0000959 // When we're overloading in C, we allow a special kind of pointer
960 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +0000961 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +0000962 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000963 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000964 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +0000965 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +0000966 return true;
967 }
968
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000969 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +0000970 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000971 // An rvalue of type "pointer to cv D," where D is a class type,
972 // can be converted to an rvalue of type "pointer to cv B," where
973 // B is a base class (clause 10) of D. If B is an inaccessible
974 // (clause 11) or ambiguous (10.2) base class of D, a program that
975 // necessitates this conversion is ill-formed. The result of the
976 // conversion is a pointer to the base class sub-object of the
977 // derived class object. The null pointer value is converted to
978 // the null pointer value of the destination type.
979 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000980 // Note that we do not check for ambiguity or inaccessibility
981 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +0000982 if (getLangOptions().CPlusPlus &&
983 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorcb7de522008-11-26 23:31:11 +0000984 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000985 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +0000986 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000987 ToType, Context);
988 return true;
989 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000990
Douglas Gregorc7887512008-12-19 19:13:09 +0000991 return false;
992}
993
994/// isObjCPointerConversion - Determines whether this is an
995/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
996/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +0000997bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +0000998 QualType& ConvertedType,
999 bool &IncompatibleObjC) {
1000 if (!getLangOptions().ObjC1)
1001 return false;
1002
Steve Naroff14108da2009-07-10 23:34:53 +00001003 // First, we handle all conversions on ObjC object pointer types.
1004 const ObjCObjectPointerType* ToObjCPtr = ToType->getAsObjCObjectPointerType();
Mike Stump1eb44332009-09-09 15:08:12 +00001005 const ObjCObjectPointerType *FromObjCPtr =
Steve Naroff14108da2009-07-10 23:34:53 +00001006 FromType->getAsObjCObjectPointerType();
Douglas Gregorc7887512008-12-19 19:13:09 +00001007
Steve Naroff14108da2009-07-10 23:34:53 +00001008 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001009 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001010 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001011 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001012 ConvertedType = ToType;
1013 return true;
1014 }
1015 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001016 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001017 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001018 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001019 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001020 ConvertedType = ToType;
1021 return true;
1022 }
1023 // Objective C++: We're able to convert from a pointer to an
1024 // interface to a pointer to a different interface.
1025 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1026 ConvertedType = ToType;
1027 return true;
1028 }
1029
1030 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1031 // Okay: this is some kind of implicit downcast of Objective-C
1032 // interfaces, which is permitted. However, we're going to
1033 // complain about it.
1034 IncompatibleObjC = true;
1035 ConvertedType = FromType;
1036 return true;
1037 }
Mike Stump1eb44332009-09-09 15:08:12 +00001038 }
Steve Naroff14108da2009-07-10 23:34:53 +00001039 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001040 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001041 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001042 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001043 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001044 ToPointeeType = ToBlockPtr->getPointeeType();
1045 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001046 return false;
1047
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001048 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001049 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001050 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001051 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001052 FromPointeeType = FromBlockPtr->getPointeeType();
1053 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001054 return false;
1055
Douglas Gregorc7887512008-12-19 19:13:09 +00001056 // If we have pointers to pointers, recursively check whether this
1057 // is an Objective-C conversion.
1058 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1059 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1060 IncompatibleObjC)) {
1061 // We always complain about this conversion.
1062 IncompatibleObjC = true;
1063 ConvertedType = ToType;
1064 return true;
1065 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001066 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001067 // differences in the argument and result types are in Objective-C
1068 // pointer conversions. If so, we permit the conversion (but
1069 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001070 const FunctionProtoType *FromFunctionType
Douglas Gregor72564e72009-02-26 23:50:07 +00001071 = FromPointeeType->getAsFunctionProtoType();
1072 const FunctionProtoType *ToFunctionType
1073 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregorc7887512008-12-19 19:13:09 +00001074 if (FromFunctionType && ToFunctionType) {
1075 // If the function types are exactly the same, this isn't an
1076 // Objective-C pointer conversion.
1077 if (Context.getCanonicalType(FromPointeeType)
1078 == Context.getCanonicalType(ToPointeeType))
1079 return false;
1080
1081 // Perform the quick checks that will tell us whether these
1082 // function types are obviously different.
1083 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1084 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1085 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1086 return false;
1087
1088 bool HasObjCConversion = false;
1089 if (Context.getCanonicalType(FromFunctionType->getResultType())
1090 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1091 // Okay, the types match exactly. Nothing to do.
1092 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1093 ToFunctionType->getResultType(),
1094 ConvertedType, IncompatibleObjC)) {
1095 // Okay, we have an Objective-C pointer conversion.
1096 HasObjCConversion = true;
1097 } else {
1098 // Function types are too different. Abort.
1099 return false;
1100 }
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Douglas Gregorc7887512008-12-19 19:13:09 +00001102 // Check argument types.
1103 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1104 ArgIdx != NumArgs; ++ArgIdx) {
1105 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1106 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1107 if (Context.getCanonicalType(FromArgType)
1108 == Context.getCanonicalType(ToArgType)) {
1109 // Okay, the types match exactly. Nothing to do.
1110 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1111 ConvertedType, IncompatibleObjC)) {
1112 // Okay, we have an Objective-C pointer conversion.
1113 HasObjCConversion = true;
1114 } else {
1115 // Argument types are too different. Abort.
1116 return false;
1117 }
1118 }
1119
1120 if (HasObjCConversion) {
1121 // We had an Objective-C conversion. Allow this pointer
1122 // conversion, but complain about it.
1123 ConvertedType = ToType;
1124 IncompatibleObjC = true;
1125 return true;
1126 }
1127 }
1128
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001129 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001130}
1131
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001132/// CheckPointerConversion - Check the pointer conversion from the
1133/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001134/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001135/// conversions for which IsPointerConversion has already returned
1136/// true. It returns true and produces a diagnostic if there was an
1137/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001138bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
1139 CastExpr::CastKind &Kind) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001140 QualType FromType = From->getType();
1141
Ted Kremenek6217b802009-07-29 21:53:49 +00001142 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1143 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001144 QualType FromPointeeType = FromPtrType->getPointeeType(),
1145 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001146
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001147 if (FromPointeeType->isRecordType() &&
1148 ToPointeeType->isRecordType()) {
1149 // We must have a derived-to-base conversion. Check an
1150 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001151 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1152 From->getExprLoc(),
1153 From->getSourceRange()))
1154 return true;
1155
1156 // The conversion was successful.
1157 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001158 }
1159 }
Mike Stump1eb44332009-09-09 15:08:12 +00001160 if (const ObjCObjectPointerType *FromPtrType =
Steve Naroff14108da2009-07-10 23:34:53 +00001161 FromType->getAsObjCObjectPointerType())
Mike Stump1eb44332009-09-09 15:08:12 +00001162 if (const ObjCObjectPointerType *ToPtrType =
Steve Naroff14108da2009-07-10 23:34:53 +00001163 ToType->getAsObjCObjectPointerType()) {
1164 // Objective-C++ conversions are always okay.
1165 // FIXME: We should have a different class of conversions for the
1166 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001167 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001168 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001169
Steve Naroff14108da2009-07-10 23:34:53 +00001170 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001171 return false;
1172}
1173
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001174/// IsMemberPointerConversion - Determines whether the conversion of the
1175/// expression From, which has the (possibly adjusted) type FromType, can be
1176/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1177/// If so, returns true and places the converted type (that might differ from
1178/// ToType in its cv-qualifiers at some level) into ConvertedType.
1179bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Mike Stump1eb44332009-09-09 15:08:12 +00001180 QualType ToType, QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001181 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001182 if (!ToTypePtr)
1183 return false;
1184
1185 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1186 if (From->isNullPointerConstant(Context)) {
1187 ConvertedType = ToType;
1188 return true;
1189 }
1190
1191 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001192 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001193 if (!FromTypePtr)
1194 return false;
1195
1196 // A pointer to member of B can be converted to a pointer to member of D,
1197 // where D is derived from B (C++ 4.11p2).
1198 QualType FromClass(FromTypePtr->getClass(), 0);
1199 QualType ToClass(ToTypePtr->getClass(), 0);
1200 // FIXME: What happens when these are dependent? Is this function even called?
1201
1202 if (IsDerivedFrom(ToClass, FromClass)) {
1203 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1204 ToClass.getTypePtr());
1205 return true;
1206 }
1207
1208 return false;
1209}
1210
1211/// CheckMemberPointerConversion - Check the member pointer conversion from the
1212/// expression From to the type ToType. This routine checks for ambiguous or
1213/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1214/// for which IsMemberPointerConversion has already returned true. It returns
1215/// true and produces a diagnostic if there was an error, or returns false
1216/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001217bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001218 CastExpr::CastKind &Kind) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001219 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001220 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001221 if (!FromPtrType) {
1222 // This must be a null pointer to member pointer conversion
Mike Stump1eb44332009-09-09 15:08:12 +00001223 assert(From->isNullPointerConstant(Context) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001224 "Expr must be null pointer constant!");
1225 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001226 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001227 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001228
Ted Kremenek6217b802009-07-29 21:53:49 +00001229 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001230 assert(ToPtrType && "No member pointer cast has a target type "
1231 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001232
Sebastian Redl21593ac2009-01-28 18:33:18 +00001233 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1234 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001235
Sebastian Redl21593ac2009-01-28 18:33:18 +00001236 // FIXME: What about dependent types?
1237 assert(FromClass->isRecordType() && "Pointer into non-class.");
1238 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001239
Sebastian Redl21593ac2009-01-28 18:33:18 +00001240 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1241 /*DetectVirtual=*/true);
1242 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1243 assert(DerivationOkay &&
1244 "Should not have been called if derivation isn't OK.");
1245 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001246
Sebastian Redl21593ac2009-01-28 18:33:18 +00001247 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1248 getUnqualifiedType())) {
1249 // Derivation is ambiguous. Redo the check to find the exact paths.
1250 Paths.clear();
1251 Paths.setRecordingPaths(true);
1252 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1253 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1254 (void)StillOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001255
Sebastian Redl21593ac2009-01-28 18:33:18 +00001256 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1257 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1258 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1259 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001260 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001261
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001262 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001263 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1264 << FromClass << ToClass << QualType(VBase, 0)
1265 << From->getSourceRange();
1266 return true;
1267 }
1268
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001269 // Must be a base to derived member conversion.
1270 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001271 return false;
1272}
1273
Douglas Gregor98cd5992008-10-21 23:43:52 +00001274/// IsQualificationConversion - Determines whether the conversion from
1275/// an rvalue of type FromType to ToType is a qualification conversion
1276/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001277bool
1278Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001279 FromType = Context.getCanonicalType(FromType);
1280 ToType = Context.getCanonicalType(ToType);
1281
1282 // If FromType and ToType are the same type, this is not a
1283 // qualification conversion.
1284 if (FromType == ToType)
1285 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001286
Douglas Gregor98cd5992008-10-21 23:43:52 +00001287 // (C++ 4.4p4):
1288 // A conversion can add cv-qualifiers at levels other than the first
1289 // in multi-level pointers, subject to the following rules: [...]
1290 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001291 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001292 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001293 // Within each iteration of the loop, we check the qualifiers to
1294 // determine if this still looks like a qualification
1295 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001296 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001297 // until there are no more pointers or pointers-to-members left to
1298 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001299 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001300
1301 // -- for every j > 0, if const is in cv 1,j then const is in cv
1302 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001303 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001304 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001305
Douglas Gregor98cd5992008-10-21 23:43:52 +00001306 // -- if the cv 1,j and cv 2,j are different, then const is in
1307 // every cv for 0 < k < j.
1308 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001309 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001310 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001311
Douglas Gregor98cd5992008-10-21 23:43:52 +00001312 // Keep track of whether all prior cv-qualifiers in the "to" type
1313 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001314 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001315 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001316 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001317
1318 // We are left with FromType and ToType being the pointee types
1319 // after unwrapping the original FromType and ToType the same number
1320 // of types. If we unwrapped any pointers, and if FromType and
1321 // ToType have the same unqualified type (since we checked
1322 // qualifiers above), then this is a qualification conversion.
1323 return UnwrappedAnyPointer &&
1324 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1325}
1326
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001327/// \brief Given a function template or function, extract the function template
1328/// declaration (if any) and the underlying function declaration.
1329template<typename T>
1330static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1331 FunctionTemplateDecl *&FunctionTemplate) {
1332 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1333 if (FunctionTemplate)
1334 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1335 else
1336 Function = cast<T>(Orig);
1337}
1338
Douglas Gregor734d9862009-01-30 23:27:23 +00001339/// Determines whether there is a user-defined conversion sequence
1340/// (C++ [over.ics.user]) that converts expression From to the type
1341/// ToType. If such a conversion exists, User will contain the
1342/// user-defined conversion sequence that performs such a conversion
1343/// and this routine will return true. Otherwise, this routine returns
1344/// false and User is unspecified.
1345///
1346/// \param AllowConversionFunctions true if the conversion should
1347/// consider conversion functions at all. If false, only constructors
1348/// will be considered.
1349///
1350/// \param AllowExplicit true if the conversion should consider C++0x
1351/// "explicit" conversion functions as well as non-explicit conversion
1352/// functions (C++0x [class.conv.fct]p2).
Sebastian Redle2b68332009-04-12 17:16:29 +00001353///
1354/// \param ForceRValue true if the expression should be treated as an rvalue
1355/// for overload resolution.
Mike Stump1eb44332009-09-09 15:08:12 +00001356bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001357 UserDefinedConversionSequence& User,
Douglas Gregor734d9862009-01-30 23:27:23 +00001358 bool AllowConversionFunctions,
Mike Stump1eb44332009-09-09 15:08:12 +00001359 bool AllowExplicit, bool ForceRValue) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001360 OverloadCandidateSet CandidateSet;
Ted Kremenek6217b802009-07-29 21:53:49 +00001361 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001362 if (CXXRecordDecl *ToRecordDecl
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001363 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1364 // C++ [over.match.ctor]p1:
1365 // When objects of class type are direct-initialized (8.5), or
1366 // copy-initialized from an expression of the same or a
1367 // derived class type (8.5), overload resolution selects the
1368 // constructor. [...] For copy-initialization, the candidate
1369 // functions are all the converting constructors (12.3.1) of
1370 // that class. The argument list is the expression-list within
1371 // the parentheses of the initializer.
Mike Stump1eb44332009-09-09 15:08:12 +00001372 DeclarationName ConstructorName
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001373 = Context.DeclarationNames.getCXXConstructorName(
1374 Context.getCanonicalType(ToType).getUnqualifiedType());
1375 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump1eb44332009-09-09 15:08:12 +00001376 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001377 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001378 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00001379 // Find the constructor (which may be a template).
1380 CXXConstructorDecl *Constructor = 0;
1381 FunctionTemplateDecl *ConstructorTmpl
1382 = dyn_cast<FunctionTemplateDecl>(*Con);
1383 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001384 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001385 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1386 else
1387 Constructor = cast<CXXConstructorDecl>(*Con);
Mike Stump1eb44332009-09-09 15:08:12 +00001388
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001389 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001390 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001391 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001392 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
Douglas Gregordec06662009-08-21 18:42:58 +00001393 1, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00001394 /*SuppressUserConversions=*/true,
Douglas Gregordec06662009-08-21 18:42:58 +00001395 ForceRValue);
1396 else
1397 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1398 /*SuppressUserConversions=*/true, ForceRValue);
1399 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001400 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001401 }
1402 }
1403
Douglas Gregor734d9862009-01-30 23:27:23 +00001404 if (!AllowConversionFunctions) {
1405 // Don't allow any conversion functions to enter the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00001406 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1407 PDiag(0)
Anders Carlssonb7906612009-08-26 23:45:07 +00001408 << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001409 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001410 } else if (const RecordType *FromRecordType
Ted Kremenek6217b802009-07-29 21:53:49 +00001411 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001412 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001413 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1414 // Add all of the conversion functions as candidates.
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001415 OverloadedFunctionDecl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001416 = FromRecordDecl->getVisibleConversionFunctions();
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001417 for (OverloadedFunctionDecl::function_iterator Func
1418 = Conversions->function_begin();
1419 Func != Conversions->function_end(); ++Func) {
1420 CXXConversionDecl *Conv;
1421 FunctionTemplateDecl *ConvTemplate;
1422 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1423 if (ConvTemplate)
1424 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1425 else
1426 Conv = dyn_cast<CXXConversionDecl>(*Func);
1427
1428 if (AllowExplicit || !Conv->isExplicit()) {
1429 if (ConvTemplate)
1430 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1431 CandidateSet);
1432 else
1433 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1434 }
1435 }
1436 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001437 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001438
1439 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001440 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001441 case OR_Success:
1442 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001443 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001444 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1445 // C++ [over.ics.user]p1:
1446 // If the user-defined conversion is specified by a
1447 // constructor (12.3.1), the initial standard conversion
1448 // sequence converts the source type to the type required by
1449 // the argument of the constructor.
1450 //
1451 // FIXME: What about ellipsis conversions?
1452 QualType ThisType = Constructor->getThisType(Context);
1453 User.Before = Best->Conversions[0].Standard;
1454 User.ConversionFunction = Constructor;
1455 User.After.setAsIdentityConversion();
Mike Stump1eb44332009-09-09 15:08:12 +00001456 User.After.FromTypePtr
Ted Kremenek6217b802009-07-29 21:53:49 +00001457 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor60d62c22008-10-31 16:23:19 +00001458 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1459 return true;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001460 } else if (CXXConversionDecl *Conversion
1461 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1462 // C++ [over.ics.user]p1:
1463 //
1464 // [...] If the user-defined conversion is specified by a
1465 // conversion function (12.3.2), the initial standard
1466 // conversion sequence converts the source type to the
1467 // implicit object parameter of the conversion function.
1468 User.Before = Best->Conversions[0].Standard;
1469 User.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00001470
1471 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001472 // The second standard conversion sequence converts the
1473 // result of the user-defined conversion to the target type
1474 // for the sequence. Since an implicit conversion sequence
1475 // is an initialization, the special rules for
1476 // initialization by user-defined conversion apply when
1477 // selecting the best user-defined conversion for a
1478 // user-defined conversion sequence (see 13.3.3 and
1479 // 13.3.3.1).
1480 User.After = Best->FinalConversion;
1481 return true;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001482 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001483 assert(false && "Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001484 return false;
1485 }
Mike Stump1eb44332009-09-09 15:08:12 +00001486
Douglas Gregor60d62c22008-10-31 16:23:19 +00001487 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001488 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001489 // No conversion here! We're done.
1490 return false;
1491
1492 case OR_Ambiguous:
1493 // FIXME: See C++ [over.best.ics]p10 for the handling of
1494 // ambiguous conversion sequences.
1495 return false;
1496 }
1497
1498 return false;
1499}
1500
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001501/// CompareImplicitConversionSequences - Compare two implicit
1502/// conversion sequences to determine whether one is better than the
1503/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00001504ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001505Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1506 const ImplicitConversionSequence& ICS2)
1507{
1508 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1509 // conversion sequences (as defined in 13.3.3.1)
1510 // -- a standard conversion sequence (13.3.3.1.1) is a better
1511 // conversion sequence than a user-defined conversion sequence or
1512 // an ellipsis conversion sequence, and
1513 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1514 // conversion sequence than an ellipsis conversion sequence
1515 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00001516 //
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001517 if (ICS1.ConversionKind < ICS2.ConversionKind)
1518 return ImplicitConversionSequence::Better;
1519 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1520 return ImplicitConversionSequence::Worse;
1521
1522 // Two implicit conversion sequences of the same form are
1523 // indistinguishable conversion sequences unless one of the
1524 // following rules apply: (C++ 13.3.3.2p3):
1525 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1526 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump1eb44332009-09-09 15:08:12 +00001527 else if (ICS1.ConversionKind ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001528 ImplicitConversionSequence::UserDefinedConversion) {
1529 // User-defined conversion sequence U1 is a better conversion
1530 // sequence than another user-defined conversion sequence U2 if
1531 // they contain the same user-defined conversion function or
1532 // constructor and if the second standard conversion sequence of
1533 // U1 is better than the second standard conversion sequence of
1534 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001535 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001536 ICS2.UserDefined.ConversionFunction)
1537 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1538 ICS2.UserDefined.After);
1539 }
1540
1541 return ImplicitConversionSequence::Indistinguishable;
1542}
1543
1544/// CompareStandardConversionSequences - Compare two standard
1545/// conversion sequences to determine whether one is better than the
1546/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001547ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001548Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1549 const StandardConversionSequence& SCS2)
1550{
1551 // Standard conversion sequence S1 is a better conversion sequence
1552 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1553
1554 // -- S1 is a proper subsequence of S2 (comparing the conversion
1555 // sequences in the canonical form defined by 13.3.3.1.1,
1556 // excluding any Lvalue Transformation; the identity conversion
1557 // sequence is considered to be a subsequence of any
1558 // non-identity conversion sequence) or, if not that,
1559 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1560 // Neither is a proper subsequence of the other. Do nothing.
1561 ;
1562 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1563 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001564 (SCS1.Second == ICK_Identity &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001565 SCS1.Third == ICK_Identity))
1566 // SCS1 is a proper subsequence of SCS2.
1567 return ImplicitConversionSequence::Better;
1568 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1569 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001570 (SCS2.Second == ICK_Identity &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001571 SCS2.Third == ICK_Identity))
1572 // SCS2 is a proper subsequence of SCS1.
1573 return ImplicitConversionSequence::Worse;
1574
1575 // -- the rank of S1 is better than the rank of S2 (by the rules
1576 // defined below), or, if not that,
1577 ImplicitConversionRank Rank1 = SCS1.getRank();
1578 ImplicitConversionRank Rank2 = SCS2.getRank();
1579 if (Rank1 < Rank2)
1580 return ImplicitConversionSequence::Better;
1581 else if (Rank2 < Rank1)
1582 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001583
Douglas Gregor57373262008-10-22 14:17:15 +00001584 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1585 // are indistinguishable unless one of the following rules
1586 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00001587
Douglas Gregor57373262008-10-22 14:17:15 +00001588 // A conversion that is not a conversion of a pointer, or
1589 // pointer to member, to bool is better than another conversion
1590 // that is such a conversion.
1591 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1592 return SCS2.isPointerConversionToBool()
1593 ? ImplicitConversionSequence::Better
1594 : ImplicitConversionSequence::Worse;
1595
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001596 // C++ [over.ics.rank]p4b2:
1597 //
1598 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001599 // conversion of B* to A* is better than conversion of B* to
1600 // void*, and conversion of A* to void* is better than conversion
1601 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00001602 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001603 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001604 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001605 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001606 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1607 // Exactly one of the conversion sequences is a conversion to
1608 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001609 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1610 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001611 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1612 // Neither conversion sequence converts to a void pointer; compare
1613 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001614 if (ImplicitConversionSequence::CompareKind DerivedCK
1615 = CompareDerivedToBaseConversions(SCS1, SCS2))
1616 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001617 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1618 // Both conversion sequences are conversions to void
1619 // pointers. Compare the source types to determine if there's an
1620 // inheritance relationship in their sources.
1621 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1622 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1623
1624 // Adjust the types we're converting from via the array-to-pointer
1625 // conversion, if we need to.
1626 if (SCS1.First == ICK_Array_To_Pointer)
1627 FromType1 = Context.getArrayDecayedType(FromType1);
1628 if (SCS2.First == ICK_Array_To_Pointer)
1629 FromType2 = Context.getArrayDecayedType(FromType2);
1630
Mike Stump1eb44332009-09-09 15:08:12 +00001631 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001632 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001633 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001634 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001635
1636 if (IsDerivedFrom(FromPointee2, FromPointee1))
1637 return ImplicitConversionSequence::Better;
1638 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1639 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001640
1641 // Objective-C++: If one interface is more specific than the
1642 // other, it is the better one.
1643 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1644 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1645 if (FromIface1 && FromIface1) {
1646 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1647 return ImplicitConversionSequence::Better;
1648 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1649 return ImplicitConversionSequence::Worse;
1650 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001651 }
Douglas Gregor57373262008-10-22 14:17:15 +00001652
1653 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1654 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00001655 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001656 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001657 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001658
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001659 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001660 // C++0x [over.ics.rank]p3b4:
1661 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1662 // implicit object parameter of a non-static member function declared
1663 // without a ref-qualifier, and S1 binds an rvalue reference to an
1664 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00001665 // FIXME: We don't know if we're dealing with the implicit object parameter,
1666 // or if the member function in this case has a ref qualifier.
1667 // (Of course, we don't have ref qualifiers yet.)
1668 if (SCS1.RRefBinding != SCS2.RRefBinding)
1669 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1670 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001671
1672 // C++ [over.ics.rank]p3b4:
1673 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1674 // which the references refer are the same type except for
1675 // top-level cv-qualifiers, and the type to which the reference
1676 // initialized by S2 refers is more cv-qualified than the type
1677 // to which the reference initialized by S1 refers.
Sebastian Redla9845802009-03-29 15:27:50 +00001678 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1679 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001680 T1 = Context.getCanonicalType(T1);
1681 T2 = Context.getCanonicalType(T2);
1682 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1683 if (T2.isMoreQualifiedThan(T1))
1684 return ImplicitConversionSequence::Better;
1685 else if (T1.isMoreQualifiedThan(T2))
1686 return ImplicitConversionSequence::Worse;
1687 }
1688 }
Douglas Gregor57373262008-10-22 14:17:15 +00001689
1690 return ImplicitConversionSequence::Indistinguishable;
1691}
1692
1693/// CompareQualificationConversions - Compares two standard conversion
1694/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00001695/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1696ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00001697Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00001698 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00001699 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001700 // -- S1 and S2 differ only in their qualification conversion and
1701 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1702 // cv-qualification signature of type T1 is a proper subset of
1703 // the cv-qualification signature of type T2, and S1 is not the
1704 // deprecated string literal array-to-pointer conversion (4.2).
1705 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1706 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1707 return ImplicitConversionSequence::Indistinguishable;
1708
1709 // FIXME: the example in the standard doesn't use a qualification
1710 // conversion (!)
1711 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1712 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1713 T1 = Context.getCanonicalType(T1);
1714 T2 = Context.getCanonicalType(T2);
1715
1716 // If the types are the same, we won't learn anything by unwrapped
1717 // them.
1718 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1719 return ImplicitConversionSequence::Indistinguishable;
1720
Mike Stump1eb44332009-09-09 15:08:12 +00001721 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00001722 = ImplicitConversionSequence::Indistinguishable;
1723 while (UnwrapSimilarPointerTypes(T1, T2)) {
1724 // Within each iteration of the loop, we check the qualifiers to
1725 // determine if this still looks like a qualification
1726 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001727 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001728 // until there are no more pointers or pointers-to-members left
1729 // to unwrap. This essentially mimics what
1730 // IsQualificationConversion does, but here we're checking for a
1731 // strict subset of qualifiers.
1732 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1733 // The qualifiers are the same, so this doesn't tell us anything
1734 // about how the sequences rank.
1735 ;
1736 else if (T2.isMoreQualifiedThan(T1)) {
1737 // T1 has fewer qualifiers, so it could be the better sequence.
1738 if (Result == ImplicitConversionSequence::Worse)
1739 // Neither has qualifiers that are a subset of the other's
1740 // qualifiers.
1741 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001742
Douglas Gregor57373262008-10-22 14:17:15 +00001743 Result = ImplicitConversionSequence::Better;
1744 } else if (T1.isMoreQualifiedThan(T2)) {
1745 // T2 has fewer qualifiers, so it could be the better sequence.
1746 if (Result == ImplicitConversionSequence::Better)
1747 // Neither has qualifiers that are a subset of the other's
1748 // qualifiers.
1749 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001750
Douglas Gregor57373262008-10-22 14:17:15 +00001751 Result = ImplicitConversionSequence::Worse;
1752 } else {
1753 // Qualifiers are disjoint.
1754 return ImplicitConversionSequence::Indistinguishable;
1755 }
1756
1757 // If the types after this point are equivalent, we're done.
1758 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1759 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001760 }
1761
Douglas Gregor57373262008-10-22 14:17:15 +00001762 // Check that the winning standard conversion sequence isn't using
1763 // the deprecated string literal array to pointer conversion.
1764 switch (Result) {
1765 case ImplicitConversionSequence::Better:
1766 if (SCS1.Deprecated)
1767 Result = ImplicitConversionSequence::Indistinguishable;
1768 break;
1769
1770 case ImplicitConversionSequence::Indistinguishable:
1771 break;
1772
1773 case ImplicitConversionSequence::Worse:
1774 if (SCS2.Deprecated)
1775 Result = ImplicitConversionSequence::Indistinguishable;
1776 break;
1777 }
1778
1779 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001780}
1781
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001782/// CompareDerivedToBaseConversions - Compares two standard conversion
1783/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001784/// various kinds of derived-to-base conversions (C++
1785/// [over.ics.rank]p4b3). As part of these checks, we also look at
1786/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001787ImplicitConversionSequence::CompareKind
1788Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1789 const StandardConversionSequence& SCS2) {
1790 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1791 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1792 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1793 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1794
1795 // Adjust the types we're converting from via the array-to-pointer
1796 // conversion, if we need to.
1797 if (SCS1.First == ICK_Array_To_Pointer)
1798 FromType1 = Context.getArrayDecayedType(FromType1);
1799 if (SCS2.First == ICK_Array_To_Pointer)
1800 FromType2 = Context.getArrayDecayedType(FromType2);
1801
1802 // Canonicalize all of the types.
1803 FromType1 = Context.getCanonicalType(FromType1);
1804 ToType1 = Context.getCanonicalType(ToType1);
1805 FromType2 = Context.getCanonicalType(FromType2);
1806 ToType2 = Context.getCanonicalType(ToType2);
1807
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001808 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001809 //
1810 // If class B is derived directly or indirectly from class A and
1811 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001812 //
1813 // For Objective-C, we let A, B, and C also be Objective-C
1814 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001815
1816 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00001817 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001818 SCS2.Second == ICK_Pointer_Conversion &&
1819 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1820 FromType1->isPointerType() && FromType2->isPointerType() &&
1821 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001822 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001823 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00001824 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001825 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001826 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001827 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001828 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001829 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001830
1831 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1832 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1833 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1834 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1835
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001836 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001837 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1838 if (IsDerivedFrom(ToPointee1, ToPointee2))
1839 return ImplicitConversionSequence::Better;
1840 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1841 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001842
1843 if (ToIface1 && ToIface2) {
1844 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1845 return ImplicitConversionSequence::Better;
1846 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1847 return ImplicitConversionSequence::Worse;
1848 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001849 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001850
1851 // -- conversion of B* to A* is better than conversion of C* to A*,
1852 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1853 if (IsDerivedFrom(FromPointee2, FromPointee1))
1854 return ImplicitConversionSequence::Better;
1855 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1856 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00001857
Douglas Gregorcb7de522008-11-26 23:31:11 +00001858 if (FromIface1 && FromIface2) {
1859 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1860 return ImplicitConversionSequence::Better;
1861 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1862 return ImplicitConversionSequence::Worse;
1863 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001864 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001865 }
1866
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001867 // Compare based on reference bindings.
1868 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1869 SCS1.Second == ICK_Derived_To_Base) {
1870 // -- binding of an expression of type C to a reference of type
1871 // B& is better than binding an expression of type C to a
1872 // reference of type A&,
1873 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1874 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1875 if (IsDerivedFrom(ToType1, ToType2))
1876 return ImplicitConversionSequence::Better;
1877 else if (IsDerivedFrom(ToType2, ToType1))
1878 return ImplicitConversionSequence::Worse;
1879 }
1880
Douglas Gregor225c41e2008-11-03 19:09:14 +00001881 // -- binding of an expression of type B to a reference of type
1882 // A& is better than binding an expression of type C to a
1883 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001884 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1885 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1886 if (IsDerivedFrom(FromType2, FromType1))
1887 return ImplicitConversionSequence::Better;
1888 else if (IsDerivedFrom(FromType1, FromType2))
1889 return ImplicitConversionSequence::Worse;
1890 }
1891 }
1892
1893
1894 // FIXME: conversion of A::* to B::* is better than conversion of
1895 // A::* to C::*,
1896
1897 // FIXME: conversion of B::* to C::* is better than conversion of
1898 // A::* to C::*, and
1899
Douglas Gregor225c41e2008-11-03 19:09:14 +00001900 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1901 SCS1.Second == ICK_Derived_To_Base) {
1902 // -- conversion of C to B is better than conversion of C to A,
1903 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1904 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1905 if (IsDerivedFrom(ToType1, ToType2))
1906 return ImplicitConversionSequence::Better;
1907 else if (IsDerivedFrom(ToType2, ToType1))
1908 return ImplicitConversionSequence::Worse;
1909 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001910
Douglas Gregor225c41e2008-11-03 19:09:14 +00001911 // -- conversion of B to A is better than conversion of C to A.
1912 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1913 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1914 if (IsDerivedFrom(FromType2, FromType1))
1915 return ImplicitConversionSequence::Better;
1916 else if (IsDerivedFrom(FromType1, FromType2))
1917 return ImplicitConversionSequence::Worse;
1918 }
1919 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001920
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001921 return ImplicitConversionSequence::Indistinguishable;
1922}
1923
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001924/// TryCopyInitialization - Try to copy-initialize a value of type
1925/// ToType from the expression From. Return the implicit conversion
1926/// sequence required to pass this argument, which may be a bad
1927/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00001928/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redle2b68332009-04-12 17:16:29 +00001929/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1930/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00001931ImplicitConversionSequence
1932Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001933 bool SuppressUserConversions, bool ForceRValue,
1934 bool InOverloadResolution) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00001935 if (ToType->isReferenceType()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001936 ImplicitConversionSequence ICS;
Mike Stump1eb44332009-09-09 15:08:12 +00001937 CheckReferenceInit(From, ToType,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001938 SuppressUserConversions,
1939 /*AllowExplicit=*/false,
1940 ForceRValue,
1941 &ICS);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001942 return ICS;
1943 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001944 return TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001945 SuppressUserConversions,
1946 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001947 ForceRValue,
1948 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001949 }
1950}
1951
Sebastian Redle2b68332009-04-12 17:16:29 +00001952/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1953/// the expression @p From. Returns true (and emits a diagnostic) if there was
1954/// an error, returns false if the initialization succeeded. Elidable should
1955/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1956/// differently in C++0x for this case.
Mike Stump1eb44332009-09-09 15:08:12 +00001957bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +00001958 const char* Flavor, bool Elidable) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001959 if (!getLangOptions().CPlusPlus) {
1960 // In C, argument passing is the same as performing an assignment.
1961 QualType FromType = From->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001962
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001963 AssignConvertType ConvTy =
1964 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00001965 if (ConvTy != Compatible &&
1966 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1967 ConvTy = Compatible;
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001969 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1970 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001971 }
Sebastian Redle2b68332009-04-12 17:16:29 +00001972
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001973 if (ToType->isReferenceType())
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001974 return CheckReferenceInit(From, ToType,
1975 /*SuppressUserConversions=*/false,
1976 /*AllowExplicit=*/false,
1977 /*ForceRValue=*/false);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001978
Sebastian Redle2b68332009-04-12 17:16:29 +00001979 if (!PerformImplicitConversion(From, ToType, Flavor,
1980 /*AllowExplicit=*/false, Elidable))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001981 return false;
Sebastian Redle2b68332009-04-12 17:16:29 +00001982
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001983 return Diag(From->getSourceRange().getBegin(),
1984 diag::err_typecheck_convert_incompatible)
1985 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001986}
1987
Douglas Gregor96176b32008-11-18 23:14:02 +00001988/// TryObjectArgumentInitialization - Try to initialize the object
1989/// parameter of the given member function (@c Method) from the
1990/// expression @p From.
1991ImplicitConversionSequence
1992Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1993 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1994 unsigned MethodQuals = Method->getTypeQualifiers();
1995 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1996
1997 // Set up the conversion sequence as a "bad" conversion, to allow us
1998 // to exit early.
1999 ImplicitConversionSequence ICS;
2000 ICS.Standard.setAsIdentityConversion();
2001 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2002
2003 // We need to have an object of class type.
2004 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002005 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00002006 FromType = PT->getPointeeType();
2007
2008 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002009
2010 // The implicit object parmeter is has the type "reference to cv X",
2011 // where X is the class of which the function is a member
2012 // (C++ [over.match.funcs]p4). However, when finding an implicit
2013 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00002014 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00002015 // (C++ [over.match.funcs]p5). We perform a simplified version of
2016 // reference binding here, that allows class rvalues to bind to
2017 // non-constant references.
2018
2019 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2020 // with the implicit object parameter (C++ [over.match.funcs]p5).
2021 QualType FromTypeCanon = Context.getCanonicalType(FromType);
2022 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2023 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2024 return ICS;
2025
2026 // Check that we have either the same type or a derived type. It
2027 // affects the conversion rank.
2028 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2029 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2030 ICS.Standard.Second = ICK_Identity;
2031 else if (IsDerivedFrom(FromType, ClassType))
2032 ICS.Standard.Second = ICK_Derived_To_Base;
2033 else
2034 return ICS;
2035
2036 // Success. Mark this as a reference binding.
2037 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2038 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2039 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2040 ICS.Standard.ReferenceBinding = true;
2041 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00002042 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002043 return ICS;
2044}
2045
2046/// PerformObjectArgumentInitialization - Perform initialization of
2047/// the implicit object parameter for the given Method with the given
2048/// expression.
2049bool
2050Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002051 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00002052 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00002053 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002054
Ted Kremenek6217b802009-07-29 21:53:49 +00002055 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002056 FromRecordType = PT->getPointeeType();
2057 DestType = Method->getThisType(Context);
2058 } else {
2059 FromRecordType = From->getType();
2060 DestType = ImplicitParamRecordType;
2061 }
2062
Mike Stump1eb44332009-09-09 15:08:12 +00002063 ImplicitConversionSequence ICS
Douglas Gregor96176b32008-11-18 23:14:02 +00002064 = TryObjectArgumentInitialization(From, Method);
2065 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2066 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002067 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00002068 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002069
Douglas Gregor96176b32008-11-18 23:14:02 +00002070 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssona552f7c2009-05-01 18:34:30 +00002071 CheckDerivedToBaseConversion(FromRecordType,
2072 ImplicitParamRecordType,
Douglas Gregor96176b32008-11-18 23:14:02 +00002073 From->getSourceRange().getBegin(),
2074 From->getSourceRange()))
2075 return true;
2076
Mike Stump1eb44332009-09-09 15:08:12 +00002077 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson116b7d92009-08-07 18:45:49 +00002078 /*isLvalue=*/true);
Douglas Gregor96176b32008-11-18 23:14:02 +00002079 return false;
2080}
2081
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002082/// TryContextuallyConvertToBool - Attempt to contextually convert the
2083/// expression From to bool (C++0x [conv]p3).
2084ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump1eb44332009-09-09 15:08:12 +00002085 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002086 // FIXME: Are these flags correct?
2087 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00002088 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00002089 /*ForceRValue=*/false,
2090 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002091}
2092
2093/// PerformContextuallyConvertToBool - Perform a contextual conversion
2094/// of the expression From to bool (C++0x [conv]p3).
2095bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2096 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2097 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2098 return false;
2099
Mike Stump1eb44332009-09-09 15:08:12 +00002100 return Diag(From->getSourceRange().getBegin(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002101 diag::err_typecheck_bool_condition)
2102 << From->getType() << From->getSourceRange();
2103}
2104
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002105/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00002106/// candidate functions, using the given function call arguments. If
2107/// @p SuppressUserConversions, then don't allow user-defined
2108/// conversions via constructors or conversion operators.
Sebastian Redle2b68332009-04-12 17:16:29 +00002109/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2110/// hacky way to implement the overloading rules for elidable copy
2111/// initialization in C++0x (C++0x 12.8p15).
Mike Stump1eb44332009-09-09 15:08:12 +00002112void
2113Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002114 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002115 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00002116 bool SuppressUserConversions,
Mike Stump1eb44332009-09-09 15:08:12 +00002117 bool ForceRValue) {
2118 const FunctionProtoType* Proto
Douglas Gregor72564e72009-02-26 23:50:07 +00002119 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002120 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00002121 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002122 "Use AddConversionCandidate for conversion functions");
Mike Stump1eb44332009-09-09 15:08:12 +00002123 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00002124 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00002125
Douglas Gregor88a35142008-12-22 05:46:06 +00002126 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002127 if (!isa<CXXConstructorDecl>(Method)) {
2128 // If we get here, it's because we're calling a member function
2129 // that is named without a member access expression (e.g.,
2130 // "this->f") that was either written explicitly or created
2131 // implicitly. This can happen with a qualified call to a member
2132 // function, e.g., X::f(). We use a NULL object as the implied
2133 // object argument (C++ [over.call.func]p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002134 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002135 SuppressUserConversions, ForceRValue);
2136 return;
2137 }
2138 // We treat a constructor like a non-member function, since its object
2139 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00002140 }
2141
2142
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002143 // Add this candidate
2144 CandidateSet.push_back(OverloadCandidate());
2145 OverloadCandidate& Candidate = CandidateSet.back();
2146 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00002147 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002148 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002149 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002150
2151 unsigned NumArgsInProto = Proto->getNumArgs();
2152
2153 // (C++ 13.3.2p2): A candidate function having fewer than m
2154 // parameters is viable only if it has an ellipsis in its parameter
2155 // list (8.3.5).
2156 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2157 Candidate.Viable = false;
2158 return;
2159 }
2160
2161 // (C++ 13.3.2p2): A candidate function having more than m parameters
2162 // is viable only if the (m+1)st parameter has a default argument
2163 // (8.3.6). For the purposes of overload resolution, the
2164 // parameter list is truncated on the right, so that there are
2165 // exactly m parameters.
2166 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2167 if (NumArgs < MinRequiredArgs) {
2168 // Not enough arguments.
2169 Candidate.Viable = false;
2170 return;
2171 }
2172
2173 // Determine the implicit conversion sequences for each of the
2174 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002175 Candidate.Conversions.resize(NumArgs);
2176 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2177 if (ArgIdx < NumArgsInProto) {
2178 // (C++ 13.3.2p3): for F to be a viable function, there shall
2179 // exist for each argument an implicit conversion sequence
2180 // (13.3.3.1) that converts that argument to the corresponding
2181 // parameter of F.
2182 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002183 Candidate.Conversions[ArgIdx]
2184 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002185 SuppressUserConversions, ForceRValue,
2186 /*InOverloadResolution=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00002187 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002188 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002189 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002190 break;
2191 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002192 } else {
2193 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2194 // argument for which there is no corresponding parameter is
2195 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002196 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002197 = ImplicitConversionSequence::EllipsisConversion;
2198 }
2199 }
2200}
2201
Douglas Gregor063daf62009-03-13 18:40:31 +00002202/// \brief Add all of the function declarations in the given function set to
2203/// the overload canddiate set.
2204void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2205 Expr **Args, unsigned NumArgs,
2206 OverloadCandidateSet& CandidateSet,
2207 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00002208 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor063daf62009-03-13 18:40:31 +00002209 FEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00002210 F != FEnd; ++F) {
2211 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
Mike Stump1eb44332009-09-09 15:08:12 +00002212 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00002213 SuppressUserConversions);
2214 else
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002215 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2216 /*FIXME: explicit args */false, 0, 0,
Mike Stump1eb44332009-09-09 15:08:12 +00002217 Args, NumArgs, CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00002218 SuppressUserConversions);
2219 }
Douglas Gregor063daf62009-03-13 18:40:31 +00002220}
2221
Douglas Gregor96176b32008-11-18 23:14:02 +00002222/// AddMethodCandidate - Adds the given C++ member function to the set
2223/// of candidate functions, using the given function call arguments
2224/// and the object argument (@c Object). For example, in a call
2225/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2226/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2227/// allow user-defined conversions via constructors or conversion
Sebastian Redle2b68332009-04-12 17:16:29 +00002228/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2229/// a slightly hacky way to implement the overloading rules for elidable copy
2230/// initialization in C++0x (C++0x 12.8p15).
Mike Stump1eb44332009-09-09 15:08:12 +00002231void
Douglas Gregor96176b32008-11-18 23:14:02 +00002232Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2233 Expr **Args, unsigned NumArgs,
2234 OverloadCandidateSet& CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00002235 bool SuppressUserConversions, bool ForceRValue) {
2236 const FunctionProtoType* Proto
Douglas Gregor72564e72009-02-26 23:50:07 +00002237 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002238 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002239 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor96176b32008-11-18 23:14:02 +00002240 "Use AddConversionCandidate for conversion functions");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002241 assert(!isa<CXXConstructorDecl>(Method) &&
2242 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00002243
2244 // Add this candidate
2245 CandidateSet.push_back(OverloadCandidate());
2246 OverloadCandidate& Candidate = CandidateSet.back();
2247 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002248 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002249 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002250
2251 unsigned NumArgsInProto = Proto->getNumArgs();
2252
2253 // (C++ 13.3.2p2): A candidate function having fewer than m
2254 // parameters is viable only if it has an ellipsis in its parameter
2255 // list (8.3.5).
2256 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2257 Candidate.Viable = false;
2258 return;
2259 }
2260
2261 // (C++ 13.3.2p2): A candidate function having more than m parameters
2262 // is viable only if the (m+1)st parameter has a default argument
2263 // (8.3.6). For the purposes of overload resolution, the
2264 // parameter list is truncated on the right, so that there are
2265 // exactly m parameters.
2266 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2267 if (NumArgs < MinRequiredArgs) {
2268 // Not enough arguments.
2269 Candidate.Viable = false;
2270 return;
2271 }
2272
2273 Candidate.Viable = true;
2274 Candidate.Conversions.resize(NumArgs + 1);
2275
Douglas Gregor88a35142008-12-22 05:46:06 +00002276 if (Method->isStatic() || !Object)
2277 // The implicit object argument is ignored.
2278 Candidate.IgnoreObjectArgument = true;
2279 else {
2280 // Determine the implicit conversion sequence for the object
2281 // parameter.
2282 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
Mike Stump1eb44332009-09-09 15:08:12 +00002283 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor88a35142008-12-22 05:46:06 +00002284 == ImplicitConversionSequence::BadConversion) {
2285 Candidate.Viable = false;
2286 return;
2287 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002288 }
2289
2290 // Determine the implicit conversion sequences for each of the
2291 // arguments.
2292 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2293 if (ArgIdx < NumArgsInProto) {
2294 // (C++ 13.3.2p3): for F to be a viable function, there shall
2295 // exist for each argument an implicit conversion sequence
2296 // (13.3.3.1) that converts that argument to the corresponding
2297 // parameter of F.
2298 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002299 Candidate.Conversions[ArgIdx + 1]
2300 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002301 SuppressUserConversions, ForceRValue,
Anders Carlsson08972922009-08-28 15:33:32 +00002302 /*InOverloadResolution=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00002303 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002304 == ImplicitConversionSequence::BadConversion) {
2305 Candidate.Viable = false;
2306 break;
2307 }
2308 } else {
2309 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2310 // argument for which there is no corresponding parameter is
2311 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002312 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002313 = ImplicitConversionSequence::EllipsisConversion;
2314 }
2315 }
2316}
2317
Douglas Gregor6b906862009-08-21 00:16:32 +00002318/// \brief Add a C++ member function template as a candidate to the candidate
2319/// set, using template argument deduction to produce an appropriate member
2320/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002321void
Douglas Gregor6b906862009-08-21 00:16:32 +00002322Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2323 bool HasExplicitTemplateArgs,
2324 const TemplateArgument *ExplicitTemplateArgs,
2325 unsigned NumExplicitTemplateArgs,
2326 Expr *Object, Expr **Args, unsigned NumArgs,
2327 OverloadCandidateSet& CandidateSet,
2328 bool SuppressUserConversions,
2329 bool ForceRValue) {
2330 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002331 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00002332 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002333 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00002334 // candidate functions in the usual way.113) A given name can refer to one
2335 // or more function templates and also to a set of overloaded non-template
2336 // functions. In such a case, the candidate functions generated from each
2337 // function template are combined with the set of non-template candidate
2338 // functions.
2339 TemplateDeductionInfo Info(Context);
2340 FunctionDecl *Specialization = 0;
2341 if (TemplateDeductionResult Result
2342 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2343 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2344 Args, NumArgs, Specialization, Info)) {
2345 // FIXME: Record what happened with template argument deduction, so
2346 // that we can give the user a beautiful diagnostic.
2347 (void)Result;
2348 return;
2349 }
Mike Stump1eb44332009-09-09 15:08:12 +00002350
Douglas Gregor6b906862009-08-21 00:16:32 +00002351 // Add the function template specialization produced by template argument
2352 // deduction as a candidate.
2353 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00002354 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00002355 "Specialization is not a member function?");
Mike Stump1eb44332009-09-09 15:08:12 +00002356 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002357 CandidateSet, SuppressUserConversions, ForceRValue);
2358}
2359
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002360/// \brief Add a C++ function template specialization as a candidate
2361/// in the candidate set, using template argument deduction to produce
2362/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002363void
Douglas Gregore53060f2009-06-25 22:08:12 +00002364Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002365 bool HasExplicitTemplateArgs,
2366 const TemplateArgument *ExplicitTemplateArgs,
2367 unsigned NumExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002368 Expr **Args, unsigned NumArgs,
2369 OverloadCandidateSet& CandidateSet,
2370 bool SuppressUserConversions,
2371 bool ForceRValue) {
2372 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002373 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00002374 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002375 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00002376 // candidate functions in the usual way.113) A given name can refer to one
2377 // or more function templates and also to a set of overloaded non-template
2378 // functions. In such a case, the candidate functions generated from each
2379 // function template are combined with the set of non-template candidate
2380 // functions.
2381 TemplateDeductionInfo Info(Context);
2382 FunctionDecl *Specialization = 0;
2383 if (TemplateDeductionResult Result
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002384 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2385 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2386 Args, NumArgs, Specialization, Info)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002387 // FIXME: Record what happened with template argument deduction, so
2388 // that we can give the user a beautiful diagnostic.
2389 (void)Result;
2390 return;
2391 }
Mike Stump1eb44332009-09-09 15:08:12 +00002392
Douglas Gregore53060f2009-06-25 22:08:12 +00002393 // Add the function template specialization produced by template argument
2394 // deduction as a candidate.
2395 assert(Specialization && "Missing function template specialization?");
2396 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2397 SuppressUserConversions, ForceRValue);
2398}
Mike Stump1eb44332009-09-09 15:08:12 +00002399
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002400/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00002401/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002402/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00002403/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002404/// (which may or may not be the same type as the type that the
2405/// conversion function produces).
2406void
2407Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2408 Expr *From, QualType ToType,
2409 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002410 assert(!Conversion->getDescribedFunctionTemplate() &&
2411 "Conversion function templates use AddTemplateConversionCandidate");
2412
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002413 // Add this candidate
2414 CandidateSet.push_back(OverloadCandidate());
2415 OverloadCandidate& Candidate = CandidateSet.back();
2416 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002417 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002418 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002419 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump1eb44332009-09-09 15:08:12 +00002420 Candidate.FinalConversion.FromTypePtr
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002421 = Conversion->getConversionType().getAsOpaquePtr();
2422 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2423
Douglas Gregor96176b32008-11-18 23:14:02 +00002424 // Determine the implicit conversion sequence for the implicit
2425 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002426 Candidate.Viable = true;
2427 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00002428 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002429 // Conversion functions to a different type in the base class is visible in
2430 // the derived class. So, a derived to base conversion should not participate
2431 // in overload resolution.
2432 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2433 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump1eb44332009-09-09 15:08:12 +00002434 if (Candidate.Conversions[0].ConversionKind
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002435 == ImplicitConversionSequence::BadConversion) {
2436 Candidate.Viable = false;
2437 return;
2438 }
2439
2440 // To determine what the conversion from the result of calling the
2441 // conversion function to the type we're eventually trying to
2442 // convert to (ToType), we need to synthesize a call to the
2443 // conversion function and attempt copy initialization from it. This
2444 // makes sure that we get the right semantics with respect to
2445 // lvalues/rvalues and the type. Fortunately, we can allocate this
2446 // call on the stack and we don't need its arguments to be
2447 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00002448 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002449 SourceLocation());
2450 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002451 CastExpr::CK_Unknown,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002452 &ConversionRef, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002453
2454 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00002455 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2456 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00002457 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002458 Conversion->getConversionType().getNonReferenceType(),
2459 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002460 ImplicitConversionSequence ICS =
2461 TryCopyInitialization(&Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002462 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002463 /*ForceRValue=*/false,
2464 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002465
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002466 switch (ICS.ConversionKind) {
2467 case ImplicitConversionSequence::StandardConversion:
2468 Candidate.FinalConversion = ICS.Standard;
2469 break;
2470
2471 case ImplicitConversionSequence::BadConversion:
2472 Candidate.Viable = false;
2473 break;
2474
2475 default:
Mike Stump1eb44332009-09-09 15:08:12 +00002476 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002477 "Can only end up with a standard conversion sequence or failure");
2478 }
2479}
2480
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002481/// \brief Adds a conversion function template specialization
2482/// candidate to the overload set, using template argument deduction
2483/// to deduce the template arguments of the conversion function
2484/// template from the type that we are converting to (C++
2485/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00002486void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002487Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2488 Expr *From, QualType ToType,
2489 OverloadCandidateSet &CandidateSet) {
2490 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2491 "Only conversion function templates permitted here");
2492
2493 TemplateDeductionInfo Info(Context);
2494 CXXConversionDecl *Specialization = 0;
2495 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00002496 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002497 Specialization, Info)) {
2498 // FIXME: Record what happened with template argument deduction, so
2499 // that we can give the user a beautiful diagnostic.
2500 (void)Result;
2501 return;
2502 }
Mike Stump1eb44332009-09-09 15:08:12 +00002503
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002504 // Add the conversion function template specialization produced by
2505 // template argument deduction as a candidate.
2506 assert(Specialization && "Missing function template specialization?");
2507 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2508}
2509
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002510/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2511/// converts the given @c Object to a function pointer via the
2512/// conversion function @c Conversion, and then attempts to call it
2513/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2514/// the type of function that we'll eventually be calling.
2515void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor72564e72009-02-26 23:50:07 +00002516 const FunctionProtoType *Proto,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002517 Expr *Object, Expr **Args, unsigned NumArgs,
2518 OverloadCandidateSet& CandidateSet) {
2519 CandidateSet.push_back(OverloadCandidate());
2520 OverloadCandidate& Candidate = CandidateSet.back();
2521 Candidate.Function = 0;
2522 Candidate.Surrogate = Conversion;
2523 Candidate.Viable = true;
2524 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002525 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002526 Candidate.Conversions.resize(NumArgs + 1);
2527
2528 // Determine the implicit conversion sequence for the implicit
2529 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00002530 ImplicitConversionSequence ObjectInit
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002531 = TryObjectArgumentInitialization(Object, Conversion);
2532 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2533 Candidate.Viable = false;
2534 return;
2535 }
2536
2537 // The first conversion is actually a user-defined conversion whose
2538 // first conversion is ObjectInit's standard conversion (which is
2539 // effectively a reference binding). Record it as such.
Mike Stump1eb44332009-09-09 15:08:12 +00002540 Candidate.Conversions[0].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002541 = ImplicitConversionSequence::UserDefinedConversion;
2542 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2543 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00002544 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002545 = Candidate.Conversions[0].UserDefined.Before;
2546 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2547
Mike Stump1eb44332009-09-09 15:08:12 +00002548 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002549 unsigned NumArgsInProto = Proto->getNumArgs();
2550
2551 // (C++ 13.3.2p2): A candidate function having fewer than m
2552 // parameters is viable only if it has an ellipsis in its parameter
2553 // list (8.3.5).
2554 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2555 Candidate.Viable = false;
2556 return;
2557 }
2558
2559 // Function types don't have any default arguments, so just check if
2560 // we have enough arguments.
2561 if (NumArgs < NumArgsInProto) {
2562 // Not enough arguments.
2563 Candidate.Viable = false;
2564 return;
2565 }
2566
2567 // Determine the implicit conversion sequences for each of the
2568 // arguments.
2569 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2570 if (ArgIdx < NumArgsInProto) {
2571 // (C++ 13.3.2p3): for F to be a viable function, there shall
2572 // exist for each argument an implicit conversion sequence
2573 // (13.3.3.1) that converts that argument to the corresponding
2574 // parameter of F.
2575 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002576 Candidate.Conversions[ArgIdx + 1]
2577 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002578 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002579 /*ForceRValue=*/false,
2580 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002581 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002582 == ImplicitConversionSequence::BadConversion) {
2583 Candidate.Viable = false;
2584 break;
2585 }
2586 } else {
2587 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2588 // argument for which there is no corresponding parameter is
2589 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002590 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002591 = ImplicitConversionSequence::EllipsisConversion;
2592 }
2593 }
2594}
2595
Mike Stump390b4cc2009-05-16 07:39:55 +00002596// FIXME: This will eventually be removed, once we've migrated all of the
2597// operator overloading logic over to the scheme used by binary operators, which
2598// works for template instantiation.
Douglas Gregor063daf62009-03-13 18:40:31 +00002599void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002600 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00002601 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002602 OverloadCandidateSet& CandidateSet,
2603 SourceRange OpRange) {
Douglas Gregor063daf62009-03-13 18:40:31 +00002604
2605 FunctionSet Functions;
2606
2607 QualType T1 = Args[0]->getType();
2608 QualType T2;
2609 if (NumArgs > 1)
2610 T2 = Args[1]->getType();
2611
2612 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002613 if (S)
2614 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00002615 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2616 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2617 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2618 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2619}
2620
2621/// \brief Add overload candidates for overloaded operators that are
2622/// member functions.
2623///
2624/// Add the overloaded operator candidates that are member functions
2625/// for the operator Op that was used in an operator expression such
2626/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2627/// CandidateSet will store the added overload candidates. (C++
2628/// [over.match.oper]).
2629void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2630 SourceLocation OpLoc,
2631 Expr **Args, unsigned NumArgs,
2632 OverloadCandidateSet& CandidateSet,
2633 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002634 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2635
2636 // C++ [over.match.oper]p3:
2637 // For a unary operator @ with an operand of a type whose
2638 // cv-unqualified version is T1, and for a binary operator @ with
2639 // a left operand of a type whose cv-unqualified version is T1 and
2640 // a right operand of a type whose cv-unqualified version is T2,
2641 // three sets of candidate functions, designated member
2642 // candidates, non-member candidates and built-in candidates, are
2643 // constructed as follows:
2644 QualType T1 = Args[0]->getType();
2645 QualType T2;
2646 if (NumArgs > 1)
2647 T2 = Args[1]->getType();
2648
2649 // -- If T1 is a class type, the set of member candidates is the
2650 // result of the qualified lookup of T1::operator@
2651 // (13.3.1.1.1); otherwise, the set of member candidates is
2652 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00002653 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002654 // Complete the type if it can be completed. Otherwise, we're done.
2655 if (RequireCompleteType(OpLoc, T1, PartialDiagnostic(0)))
2656 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002657
2658 LookupResult Operators = LookupQualifiedName(T1Rec->getDecl(), OpName,
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002659 LookupOrdinaryName, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002660 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002661 OperEnd = Operators.end();
2662 Oper != OperEnd;
2663 ++Oper)
Mike Stump1eb44332009-09-09 15:08:12 +00002664 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002665 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor96176b32008-11-18 23:14:02 +00002666 /*SuppressUserConversions=*/false);
Douglas Gregor96176b32008-11-18 23:14:02 +00002667 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002668}
2669
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002670/// AddBuiltinCandidate - Add a candidate for a built-in
2671/// operator. ResultTy and ParamTys are the result and parameter types
2672/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002673/// arguments being passed to the candidate. IsAssignmentOperator
2674/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002675/// operator. NumContextualBoolArguments is the number of arguments
2676/// (at the beginning of the argument list) that will be contextually
2677/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00002678void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002679 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002680 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002681 bool IsAssignmentOperator,
2682 unsigned NumContextualBoolArguments) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002683 // Add this candidate
2684 CandidateSet.push_back(OverloadCandidate());
2685 OverloadCandidate& Candidate = CandidateSet.back();
2686 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00002687 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002688 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002689 Candidate.BuiltinTypes.ResultTy = ResultTy;
2690 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2691 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2692
2693 // Determine the implicit conversion sequences for each of the
2694 // arguments.
2695 Candidate.Viable = true;
2696 Candidate.Conversions.resize(NumArgs);
2697 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002698 // C++ [over.match.oper]p4:
2699 // For the built-in assignment operators, conversions of the
2700 // left operand are restricted as follows:
2701 // -- no temporaries are introduced to hold the left operand, and
2702 // -- no user-defined conversions are applied to the left
2703 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00002704 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002705 //
2706 // We block these conversions by turning off user-defined
2707 // conversions, since that is the only way that initialization of
2708 // a reference to a non-class type can occur from something that
2709 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002710 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00002711 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002712 "Contextual conversion to bool requires bool type");
2713 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2714 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002715 Candidate.Conversions[ArgIdx]
2716 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00002717 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002718 /*ForceRValue=*/false,
2719 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002720 }
Mike Stump1eb44332009-09-09 15:08:12 +00002721 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002722 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002723 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002724 break;
2725 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002726 }
2727}
2728
2729/// BuiltinCandidateTypeSet - A set of types that will be used for the
2730/// candidate operator functions for built-in operators (C++
2731/// [over.built]). The types are separated into pointer types and
2732/// enumeration types.
2733class BuiltinCandidateTypeSet {
2734 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002735 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002736
2737 /// PointerTypes - The set of pointer types that will be used in the
2738 /// built-in candidates.
2739 TypeSet PointerTypes;
2740
Sebastian Redl78eb8742009-04-19 21:53:20 +00002741 /// MemberPointerTypes - The set of member pointer types that will be
2742 /// used in the built-in candidates.
2743 TypeSet MemberPointerTypes;
2744
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002745 /// EnumerationTypes - The set of enumeration types that will be
2746 /// used in the built-in candidates.
2747 TypeSet EnumerationTypes;
2748
Douglas Gregor5842ba92009-08-24 15:23:48 +00002749 /// Sema - The semantic analysis instance where we are building the
2750 /// candidate type set.
2751 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00002752
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002753 /// Context - The AST context in which we will build the type sets.
2754 ASTContext &Context;
2755
Sebastian Redl78eb8742009-04-19 21:53:20 +00002756 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2757 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002758
2759public:
2760 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002761 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002762
Mike Stump1eb44332009-09-09 15:08:12 +00002763 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00002764 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002765
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002766 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2767 bool AllowExplicitConversions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002768
2769 /// pointer_begin - First pointer type found;
2770 iterator pointer_begin() { return PointerTypes.begin(); }
2771
Sebastian Redl78eb8742009-04-19 21:53:20 +00002772 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002773 iterator pointer_end() { return PointerTypes.end(); }
2774
Sebastian Redl78eb8742009-04-19 21:53:20 +00002775 /// member_pointer_begin - First member pointer type found;
2776 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2777
2778 /// member_pointer_end - Past the last member pointer type found;
2779 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2780
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002781 /// enumeration_begin - First enumeration type found;
2782 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2783
Sebastian Redl78eb8742009-04-19 21:53:20 +00002784 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002785 iterator enumeration_end() { return EnumerationTypes.end(); }
2786};
2787
Sebastian Redl78eb8742009-04-19 21:53:20 +00002788/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002789/// the set of pointer types along with any more-qualified variants of
2790/// that type. For example, if @p Ty is "int const *", this routine
2791/// will add "int const *", "int const volatile *", "int const
2792/// restrict *", and "int const volatile restrict *" to the set of
2793/// pointer types. Returns true if the add of @p Ty itself succeeded,
2794/// false otherwise.
Sebastian Redl78eb8742009-04-19 21:53:20 +00002795bool
2796BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002797 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002798 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002799 return false;
2800
Ted Kremenek6217b802009-07-29 21:53:49 +00002801 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002802 QualType PointeeTy = PointerTy->getPointeeType();
2803 // FIXME: Optimize this so that we don't keep trying to add the same types.
2804
Mike Stump390b4cc2009-05-16 07:39:55 +00002805 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2806 // pointer conversions that don't cast away constness?
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002807 if (!PointeeTy.isConstQualified())
Sebastian Redl78eb8742009-04-19 21:53:20 +00002808 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002809 (Context.getPointerType(PointeeTy.withConst()));
2810 if (!PointeeTy.isVolatileQualified())
Sebastian Redl78eb8742009-04-19 21:53:20 +00002811 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002812 (Context.getPointerType(PointeeTy.withVolatile()));
2813 if (!PointeeTy.isRestrictQualified())
Sebastian Redl78eb8742009-04-19 21:53:20 +00002814 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002815 (Context.getPointerType(PointeeTy.withRestrict()));
2816 }
2817
2818 return true;
2819}
2820
Sebastian Redl78eb8742009-04-19 21:53:20 +00002821/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2822/// to the set of pointer types along with any more-qualified variants of
2823/// that type. For example, if @p Ty is "int const *", this routine
2824/// will add "int const *", "int const volatile *", "int const
2825/// restrict *", and "int const volatile restrict *" to the set of
2826/// pointer types. Returns true if the add of @p Ty itself succeeded,
2827/// false otherwise.
2828bool
2829BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2830 QualType Ty) {
2831 // Insert this type.
2832 if (!MemberPointerTypes.insert(Ty))
2833 return false;
2834
Ted Kremenek6217b802009-07-29 21:53:49 +00002835 if (const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>()) {
Sebastian Redl78eb8742009-04-19 21:53:20 +00002836 QualType PointeeTy = PointerTy->getPointeeType();
2837 const Type *ClassTy = PointerTy->getClass();
2838 // FIXME: Optimize this so that we don't keep trying to add the same types.
2839
2840 if (!PointeeTy.isConstQualified())
2841 AddMemberPointerWithMoreQualifiedTypeVariants
2842 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2843 if (!PointeeTy.isVolatileQualified())
2844 AddMemberPointerWithMoreQualifiedTypeVariants
2845 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2846 if (!PointeeTy.isRestrictQualified())
2847 AddMemberPointerWithMoreQualifiedTypeVariants
2848 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2849 }
2850
2851 return true;
2852}
2853
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002854/// AddTypesConvertedFrom - Add each of the types to which the type @p
2855/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00002856/// primarily interested in pointer types and enumeration types. We also
2857/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002858/// AllowUserConversions is true if we should look at the conversion
2859/// functions of a class type, and AllowExplicitConversions if we
2860/// should also include the explicit conversion functions of a class
2861/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00002862void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002863BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2864 bool AllowUserConversions,
2865 bool AllowExplicitConversions) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002866 // Only deal with canonical types.
2867 Ty = Context.getCanonicalType(Ty);
2868
2869 // Look through reference types; they aren't part of the type of an
2870 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00002871 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002872 Ty = RefTy->getPointeeType();
2873
2874 // We don't care about qualifiers on the type.
2875 Ty = Ty.getUnqualifiedType();
2876
Ted Kremenek6217b802009-07-29 21:53:49 +00002877 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002878 QualType PointeeTy = PointerTy->getPointeeType();
2879
2880 // Insert our type, and its more-qualified variants, into the set
2881 // of types.
Sebastian Redl78eb8742009-04-19 21:53:20 +00002882 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002883 return;
2884
2885 // Add 'cv void*' to our set of types.
2886 if (!Ty->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002887 QualType QualVoid
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002888 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl78eb8742009-04-19 21:53:20 +00002889 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002890 }
2891
2892 // If this is a pointer to a class type, add pointers to its bases
2893 // (with the same level of cv-qualification as the original
2894 // derived class, of course).
Ted Kremenek6217b802009-07-29 21:53:49 +00002895 if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002896 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2897 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2898 Base != ClassDecl->bases_end(); ++Base) {
2899 QualType BaseTy = Context.getCanonicalType(Base->getType());
2900 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2901
2902 // Add the pointer type, recursively, so that we get all of
2903 // the indirect base classes, too.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002904 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002905 }
2906 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00002907 } else if (Ty->isMemberPointerType()) {
2908 // Member pointers are far easier, since the pointee can't be converted.
2909 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2910 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002911 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00002912 EnumerationTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002913 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002914 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002915 if (SemaRef.RequireCompleteType(SourceLocation(), Ty, 0)) {
2916 // No conversion functions in incomplete types.
2917 return;
2918 }
Mike Stump1eb44332009-09-09 15:08:12 +00002919
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002920 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2921 // FIXME: Visit conversion functions in the base classes, too.
Mike Stump1eb44332009-09-09 15:08:12 +00002922 OverloadedFunctionDecl *Conversions
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002923 = ClassDecl->getConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00002924 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002925 = Conversions->function_begin();
2926 Func != Conversions->function_end(); ++Func) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002927 CXXConversionDecl *Conv;
2928 FunctionTemplateDecl *ConvTemplate;
2929 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
2930
Mike Stump1eb44332009-09-09 15:08:12 +00002931 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002932 // about which builtin types we can convert to.
2933 if (ConvTemplate)
2934 continue;
2935
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002936 if (AllowExplicitConversions || !Conv->isExplicit())
2937 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002938 }
2939 }
2940 }
2941}
2942
Douglas Gregor19b7b152009-08-24 13:43:27 +00002943/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
2944/// the volatile- and non-volatile-qualified assignment operators for the
2945/// given type to the candidate set.
2946static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
2947 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00002948 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00002949 unsigned NumArgs,
2950 OverloadCandidateSet &CandidateSet) {
2951 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002952
Douglas Gregor19b7b152009-08-24 13:43:27 +00002953 // T& operator=(T&, T)
2954 ParamTypes[0] = S.Context.getLValueReferenceType(T);
2955 ParamTypes[1] = T;
2956 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2957 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00002958
Douglas Gregor19b7b152009-08-24 13:43:27 +00002959 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
2960 // volatile T& operator=(volatile T&, T)
2961 ParamTypes[0] = S.Context.getLValueReferenceType(T.withVolatile());
2962 ParamTypes[1] = T;
2963 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00002964 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00002965 }
2966}
Mike Stump1eb44332009-09-09 15:08:12 +00002967
Douglas Gregor74253732008-11-19 15:42:04 +00002968/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2969/// operator overloads to the candidate set (C++ [over.built]), based
2970/// on the operator @p Op and the arguments given. For example, if the
2971/// operator is a binary '+', this routine might add "int
2972/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002973void
Mike Stump1eb44332009-09-09 15:08:12 +00002974Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor74253732008-11-19 15:42:04 +00002975 Expr **Args, unsigned NumArgs,
2976 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002977 // The set of "promoted arithmetic types", which are the arithmetic
2978 // types are that preserved by promotion (C++ [over.built]p2). Note
2979 // that the first few of these types are the promoted integral
2980 // types; these types need to be first.
2981 // FIXME: What about complex?
2982 const unsigned FirstIntegralType = 0;
2983 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00002984 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002985 LastPromotedIntegralType = 13;
2986 const unsigned FirstPromotedArithmeticType = 7,
2987 LastPromotedArithmeticType = 16;
2988 const unsigned NumArithmeticTypes = 16;
2989 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00002990 Context.BoolTy, Context.CharTy, Context.WCharTy,
2991// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002992 Context.SignedCharTy, Context.ShortTy,
2993 Context.UnsignedCharTy, Context.UnsignedShortTy,
2994 Context.IntTy, Context.LongTy, Context.LongLongTy,
2995 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2996 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2997 };
2998
2999 // Find all of the types that the arguments can convert to, but only
3000 // if the operator we're looking at has built-in operator candidates
3001 // that make use of these types.
Douglas Gregor5842ba92009-08-24 15:23:48 +00003002 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003003 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3004 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00003005 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003006 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00003007 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003008 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor74253732008-11-19 15:42:04 +00003009 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003010 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3011 true,
3012 (Op == OO_Exclaim ||
3013 Op == OO_AmpAmp ||
3014 Op == OO_PipePipe));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003015 }
3016
3017 bool isComparison = false;
3018 switch (Op) {
3019 case OO_None:
3020 case NUM_OVERLOADED_OPERATORS:
3021 assert(false && "Expected an overloaded operator");
3022 break;
3023
Douglas Gregor74253732008-11-19 15:42:04 +00003024 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00003025 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00003026 goto UnaryStar;
3027 else
3028 goto BinaryStar;
3029 break;
3030
3031 case OO_Plus: // '+' is either unary or binary
3032 if (NumArgs == 1)
3033 goto UnaryPlus;
3034 else
3035 goto BinaryPlus;
3036 break;
3037
3038 case OO_Minus: // '-' is either unary or binary
3039 if (NumArgs == 1)
3040 goto UnaryMinus;
3041 else
3042 goto BinaryMinus;
3043 break;
3044
3045 case OO_Amp: // '&' is either unary or binary
3046 if (NumArgs == 1)
3047 goto UnaryAmp;
3048 else
3049 goto BinaryAmp;
3050
3051 case OO_PlusPlus:
3052 case OO_MinusMinus:
3053 // C++ [over.built]p3:
3054 //
3055 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3056 // is either volatile or empty, there exist candidate operator
3057 // functions of the form
3058 //
3059 // VQ T& operator++(VQ T&);
3060 // T operator++(VQ T&, int);
3061 //
3062 // C++ [over.built]p4:
3063 //
3064 // For every pair (T, VQ), where T is an arithmetic type other
3065 // than bool, and VQ is either volatile or empty, there exist
3066 // candidate operator functions of the form
3067 //
3068 // VQ T& operator--(VQ T&);
3069 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00003070 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00003071 Arith < NumArithmeticTypes; ++Arith) {
3072 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00003073 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003074 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00003075
3076 // Non-volatile version.
3077 if (NumArgs == 1)
3078 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3079 else
3080 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3081
3082 // Volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003083 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor74253732008-11-19 15:42:04 +00003084 if (NumArgs == 1)
3085 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3086 else
3087 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3088 }
3089
3090 // C++ [over.built]p5:
3091 //
3092 // For every pair (T, VQ), where T is a cv-qualified or
3093 // cv-unqualified object type, and VQ is either volatile or
3094 // empty, there exist candidate operator functions of the form
3095 //
3096 // T*VQ& operator++(T*VQ&);
3097 // T*VQ& operator--(T*VQ&);
3098 // T* operator++(T*VQ&, int);
3099 // T* operator--(T*VQ&, int);
3100 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3101 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3102 // Skip pointer types that aren't pointers to object types.
Ted Kremenek6217b802009-07-29 21:53:49 +00003103 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00003104 continue;
3105
Mike Stump1eb44332009-09-09 15:08:12 +00003106 QualType ParamTypes[2] = {
3107 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00003108 };
Mike Stump1eb44332009-09-09 15:08:12 +00003109
Douglas Gregor74253732008-11-19 15:42:04 +00003110 // Without volatile
3111 if (NumArgs == 1)
3112 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3113 else
3114 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3115
3116 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3117 // With volatile
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003118 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor74253732008-11-19 15:42:04 +00003119 if (NumArgs == 1)
3120 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3121 else
3122 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3123 }
3124 }
3125 break;
3126
3127 UnaryStar:
3128 // C++ [over.built]p6:
3129 // For every cv-qualified or cv-unqualified object type T, there
3130 // exist candidate operator functions of the form
3131 //
3132 // T& operator*(T*);
3133 //
3134 // C++ [over.built]p7:
3135 // For every function type T, there exist candidate operator
3136 // functions of the form
3137 // T& operator*(T*);
3138 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3139 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3140 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00003141 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003142 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00003143 &ParamTy, Args, 1, CandidateSet);
3144 }
3145 break;
3146
3147 UnaryPlus:
3148 // C++ [over.built]p8:
3149 // For every type T, there exist candidate operator functions of
3150 // the form
3151 //
3152 // T* operator+(T*);
3153 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3154 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3155 QualType ParamTy = *Ptr;
3156 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3157 }
Mike Stump1eb44332009-09-09 15:08:12 +00003158
Douglas Gregor74253732008-11-19 15:42:04 +00003159 // Fall through
3160
3161 UnaryMinus:
3162 // C++ [over.built]p9:
3163 // For every promoted arithmetic type T, there exist candidate
3164 // operator functions of the form
3165 //
3166 // T operator+(T);
3167 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003168 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00003169 Arith < LastPromotedArithmeticType; ++Arith) {
3170 QualType ArithTy = ArithmeticTypes[Arith];
3171 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3172 }
3173 break;
3174
3175 case OO_Tilde:
3176 // C++ [over.built]p10:
3177 // For every promoted integral type T, there exist candidate
3178 // operator functions of the form
3179 //
3180 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003181 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00003182 Int < LastPromotedIntegralType; ++Int) {
3183 QualType IntTy = ArithmeticTypes[Int];
3184 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3185 }
3186 break;
3187
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003188 case OO_New:
3189 case OO_Delete:
3190 case OO_Array_New:
3191 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003192 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00003193 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003194 break;
3195
3196 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00003197 UnaryAmp:
3198 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003199 // C++ [over.match.oper]p3:
3200 // -- For the operator ',', the unary operator '&', or the
3201 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003202 break;
3203
Douglas Gregor19b7b152009-08-24 13:43:27 +00003204 case OO_EqualEqual:
3205 case OO_ExclaimEqual:
3206 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00003207 // For every pointer to member type T, there exist candidate operator
3208 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00003209 //
3210 // bool operator==(T,T);
3211 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00003212 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00003213 MemPtr = CandidateTypes.member_pointer_begin(),
3214 MemPtrEnd = CandidateTypes.member_pointer_end();
3215 MemPtr != MemPtrEnd;
3216 ++MemPtr) {
3217 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3218 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3219 }
Mike Stump1eb44332009-09-09 15:08:12 +00003220
Douglas Gregor19b7b152009-08-24 13:43:27 +00003221 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00003222
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003223 case OO_Less:
3224 case OO_Greater:
3225 case OO_LessEqual:
3226 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003227 // C++ [over.built]p15:
3228 //
3229 // For every pointer or enumeration type T, there exist
3230 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003231 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003232 // bool operator<(T, T);
3233 // bool operator>(T, T);
3234 // bool operator<=(T, T);
3235 // bool operator>=(T, T);
3236 // bool operator==(T, T);
3237 // bool operator!=(T, T);
3238 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3239 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3240 QualType ParamTypes[2] = { *Ptr, *Ptr };
3241 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3242 }
Mike Stump1eb44332009-09-09 15:08:12 +00003243 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003244 = CandidateTypes.enumeration_begin();
3245 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3246 QualType ParamTypes[2] = { *Enum, *Enum };
3247 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3248 }
3249
3250 // Fall through.
3251 isComparison = true;
3252
Douglas Gregor74253732008-11-19 15:42:04 +00003253 BinaryPlus:
3254 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003255 if (!isComparison) {
3256 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3257
3258 // C++ [over.built]p13:
3259 //
3260 // For every cv-qualified or cv-unqualified object type T
3261 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003262 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003263 // T* operator+(T*, ptrdiff_t);
3264 // T& operator[](T*, ptrdiff_t); [BELOW]
3265 // T* operator-(T*, ptrdiff_t);
3266 // T* operator+(ptrdiff_t, T*);
3267 // T& operator[](ptrdiff_t, T*); [BELOW]
3268 //
3269 // C++ [over.built]p14:
3270 //
3271 // For every T, where T is a pointer to object type, there
3272 // exist candidate operator functions of the form
3273 //
3274 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00003275 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003276 = CandidateTypes.pointer_begin();
3277 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3278 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3279
3280 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3281 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3282
3283 if (Op == OO_Plus) {
3284 // T* operator+(ptrdiff_t, T*);
3285 ParamTypes[0] = ParamTypes[1];
3286 ParamTypes[1] = *Ptr;
3287 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3288 } else {
3289 // ptrdiff_t operator-(T, T);
3290 ParamTypes[1] = *Ptr;
3291 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3292 Args, 2, CandidateSet);
3293 }
3294 }
3295 }
3296 // Fall through
3297
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003298 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00003299 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003300 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003301 // C++ [over.built]p12:
3302 //
3303 // For every pair of promoted arithmetic types L and R, there
3304 // exist candidate operator functions of the form
3305 //
3306 // LR operator*(L, R);
3307 // LR operator/(L, R);
3308 // LR operator+(L, R);
3309 // LR operator-(L, R);
3310 // bool operator<(L, R);
3311 // bool operator>(L, R);
3312 // bool operator<=(L, R);
3313 // bool operator>=(L, R);
3314 // bool operator==(L, R);
3315 // bool operator!=(L, R);
3316 //
3317 // where LR is the result of the usual arithmetic conversions
3318 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003319 //
3320 // C++ [over.built]p24:
3321 //
3322 // For every pair of promoted arithmetic types L and R, there exist
3323 // candidate operator functions of the form
3324 //
3325 // LR operator?(bool, L, R);
3326 //
3327 // where LR is the result of the usual arithmetic conversions
3328 // between types L and R.
3329 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003330 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003331 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003332 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003333 Right < LastPromotedArithmeticType; ++Right) {
3334 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00003335 QualType Result
3336 = isComparison
3337 ? Context.BoolTy
3338 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003339 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3340 }
3341 }
3342 break;
3343
3344 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00003345 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003346 case OO_Caret:
3347 case OO_Pipe:
3348 case OO_LessLess:
3349 case OO_GreaterGreater:
3350 // C++ [over.built]p17:
3351 //
3352 // For every pair of promoted integral types L and R, there
3353 // exist candidate operator functions of the form
3354 //
3355 // LR operator%(L, R);
3356 // LR operator&(L, R);
3357 // LR operator^(L, R);
3358 // LR operator|(L, R);
3359 // L operator<<(L, R);
3360 // L operator>>(L, R);
3361 //
3362 // where LR is the result of the usual arithmetic conversions
3363 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00003364 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003365 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003366 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003367 Right < LastPromotedIntegralType; ++Right) {
3368 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3369 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3370 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00003371 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003372 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3373 }
3374 }
3375 break;
3376
3377 case OO_Equal:
3378 // C++ [over.built]p20:
3379 //
3380 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00003381 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003382 // empty, there exist candidate operator functions of the form
3383 //
3384 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003385 for (BuiltinCandidateTypeSet::iterator
3386 Enum = CandidateTypes.enumeration_begin(),
3387 EnumEnd = CandidateTypes.enumeration_end();
3388 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00003389 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003390 CandidateSet);
3391 for (BuiltinCandidateTypeSet::iterator
3392 MemPtr = CandidateTypes.member_pointer_begin(),
3393 MemPtrEnd = CandidateTypes.member_pointer_end();
3394 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00003395 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003396 CandidateSet);
3397 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003398
3399 case OO_PlusEqual:
3400 case OO_MinusEqual:
3401 // C++ [over.built]p19:
3402 //
3403 // For every pair (T, VQ), where T is any type and VQ is either
3404 // volatile or empty, there exist candidate operator functions
3405 // of the form
3406 //
3407 // T*VQ& operator=(T*VQ&, T*);
3408 //
3409 // C++ [over.built]p21:
3410 //
3411 // For every pair (T, VQ), where T is a cv-qualified or
3412 // cv-unqualified object type and VQ is either volatile or
3413 // empty, there exist candidate operator functions of the form
3414 //
3415 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3416 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3417 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3418 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3419 QualType ParamTypes[2];
3420 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3421
3422 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003423 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003424 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3425 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003426
Douglas Gregor74253732008-11-19 15:42:04 +00003427 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3428 // volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003429 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003430 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3431 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003432 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003433 }
3434 // Fall through.
3435
3436 case OO_StarEqual:
3437 case OO_SlashEqual:
3438 // C++ [over.built]p18:
3439 //
3440 // For every triple (L, VQ, R), where L is an arithmetic type,
3441 // VQ is either volatile or empty, and R is a promoted
3442 // arithmetic type, there exist candidate operator functions of
3443 // the form
3444 //
3445 // VQ L& operator=(VQ L&, R);
3446 // VQ L& operator*=(VQ L&, R);
3447 // VQ L& operator/=(VQ L&, R);
3448 // VQ L& operator+=(VQ L&, R);
3449 // VQ L& operator-=(VQ L&, R);
3450 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003451 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003452 Right < LastPromotedArithmeticType; ++Right) {
3453 QualType ParamTypes[2];
3454 ParamTypes[1] = ArithmeticTypes[Right];
3455
3456 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003457 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003458 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3459 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003460
3461 // Add this built-in operator as a candidate (VQ is 'volatile').
3462 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003463 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003464 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3465 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003466 }
3467 }
3468 break;
3469
3470 case OO_PercentEqual:
3471 case OO_LessLessEqual:
3472 case OO_GreaterGreaterEqual:
3473 case OO_AmpEqual:
3474 case OO_CaretEqual:
3475 case OO_PipeEqual:
3476 // C++ [over.built]p22:
3477 //
3478 // For every triple (L, VQ, R), where L is an integral type, VQ
3479 // is either volatile or empty, and R is a promoted integral
3480 // type, there exist candidate operator functions of the form
3481 //
3482 // VQ L& operator%=(VQ L&, R);
3483 // VQ L& operator<<=(VQ L&, R);
3484 // VQ L& operator>>=(VQ L&, R);
3485 // VQ L& operator&=(VQ L&, R);
3486 // VQ L& operator^=(VQ L&, R);
3487 // VQ L& operator|=(VQ L&, R);
3488 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003489 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003490 Right < LastPromotedIntegralType; ++Right) {
3491 QualType ParamTypes[2];
3492 ParamTypes[1] = ArithmeticTypes[Right];
3493
3494 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003495 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003496 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3497
3498 // Add this built-in operator as a candidate (VQ is 'volatile').
3499 ParamTypes[0] = ArithmeticTypes[Left];
3500 ParamTypes[0].addVolatile();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003501 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003502 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3503 }
3504 }
3505 break;
3506
Douglas Gregor74253732008-11-19 15:42:04 +00003507 case OO_Exclaim: {
3508 // C++ [over.operator]p23:
3509 //
3510 // There also exist candidate operator functions of the form
3511 //
Mike Stump1eb44332009-09-09 15:08:12 +00003512 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00003513 // bool operator&&(bool, bool); [BELOW]
3514 // bool operator||(bool, bool); [BELOW]
3515 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003516 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3517 /*IsAssignmentOperator=*/false,
3518 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00003519 break;
3520 }
3521
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003522 case OO_AmpAmp:
3523 case OO_PipePipe: {
3524 // C++ [over.operator]p23:
3525 //
3526 // There also exist candidate operator functions of the form
3527 //
Douglas Gregor74253732008-11-19 15:42:04 +00003528 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003529 // bool operator&&(bool, bool);
3530 // bool operator||(bool, bool);
3531 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003532 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3533 /*IsAssignmentOperator=*/false,
3534 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003535 break;
3536 }
3537
3538 case OO_Subscript:
3539 // C++ [over.built]p13:
3540 //
3541 // For every cv-qualified or cv-unqualified object type T there
3542 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003543 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003544 // T* operator+(T*, ptrdiff_t); [ABOVE]
3545 // T& operator[](T*, ptrdiff_t);
3546 // T* operator-(T*, ptrdiff_t); [ABOVE]
3547 // T* operator+(ptrdiff_t, T*); [ABOVE]
3548 // T& operator[](ptrdiff_t, T*);
3549 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3550 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3551 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00003552 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003553 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003554
3555 // T& operator[](T*, ptrdiff_t)
3556 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3557
3558 // T& operator[](ptrdiff_t, T*);
3559 ParamTypes[0] = ParamTypes[1];
3560 ParamTypes[1] = *Ptr;
3561 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3562 }
3563 break;
3564
3565 case OO_ArrowStar:
3566 // FIXME: No support for pointer-to-members yet.
3567 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003568
3569 case OO_Conditional:
3570 // Note that we don't consider the first argument, since it has been
3571 // contextually converted to bool long ago. The candidates below are
3572 // therefore added as binary.
3573 //
3574 // C++ [over.built]p24:
3575 // For every type T, where T is a pointer or pointer-to-member type,
3576 // there exist candidate operator functions of the form
3577 //
3578 // T operator?(bool, T, T);
3579 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003580 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3581 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3582 QualType ParamTypes[2] = { *Ptr, *Ptr };
3583 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3584 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00003585 for (BuiltinCandidateTypeSet::iterator Ptr =
3586 CandidateTypes.member_pointer_begin(),
3587 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3588 QualType ParamTypes[2] = { *Ptr, *Ptr };
3589 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3590 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003591 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003592 }
3593}
3594
Douglas Gregorfa047642009-02-04 00:32:51 +00003595/// \brief Add function candidates found via argument-dependent lookup
3596/// to the set of overloading candidates.
3597///
3598/// This routine performs argument-dependent name lookup based on the
3599/// given function name (which may also be an operator name) and adds
3600/// all of the overload candidates found by ADL to the overload
3601/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00003602void
Douglas Gregorfa047642009-02-04 00:32:51 +00003603Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3604 Expr **Args, unsigned NumArgs,
3605 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003606 FunctionSet Functions;
Douglas Gregorfa047642009-02-04 00:32:51 +00003607
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003608 // Record all of the function candidates that we've already
3609 // added to the overload set, so that we don't add those same
3610 // candidates a second time.
3611 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3612 CandEnd = CandidateSet.end();
3613 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00003614 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003615 Functions.insert(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00003616 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3617 Functions.insert(FunTmpl);
3618 }
Douglas Gregorfa047642009-02-04 00:32:51 +00003619
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003620 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregorfa047642009-02-04 00:32:51 +00003621
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003622 // Erase all of the candidates we already knew about.
3623 // FIXME: This is suboptimal. Is there a better way?
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.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00003629 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3630 Functions.erase(FunTmpl);
3631 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003632
3633 // For each of the ADL candidates we found, add it to the overload
3634 // set.
3635 for (FunctionSet::iterator Func = Functions.begin(),
3636 FuncEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00003637 Func != FuncEnd; ++Func) {
3638 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
3639 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet);
3640 else
Mike Stump1eb44332009-09-09 15:08:12 +00003641 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003642 /*FIXME: explicit args */false, 0, 0,
3643 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00003644 }
Douglas Gregorfa047642009-02-04 00:32:51 +00003645}
3646
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003647/// isBetterOverloadCandidate - Determines whether the first overload
3648/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00003649bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003650Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump1eb44332009-09-09 15:08:12 +00003651 const OverloadCandidate& Cand2) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003652 // Define viable functions to be better candidates than non-viable
3653 // functions.
3654 if (!Cand2.Viable)
3655 return Cand1.Viable;
3656 else if (!Cand1.Viable)
3657 return false;
3658
Douglas Gregor88a35142008-12-22 05:46:06 +00003659 // C++ [over.match.best]p1:
3660 //
3661 // -- if F is a static member function, ICS1(F) is defined such
3662 // that ICS1(F) is neither better nor worse than ICS1(G) for
3663 // any function G, and, symmetrically, ICS1(G) is neither
3664 // better nor worse than ICS1(F).
3665 unsigned StartArg = 0;
3666 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3667 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003668
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003669 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00003670 // A viable function F1 is defined to be a better function than another
3671 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003672 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003673 unsigned NumArgs = Cand1.Conversions.size();
3674 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3675 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003676 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003677 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3678 Cand2.Conversions[ArgIdx])) {
3679 case ImplicitConversionSequence::Better:
3680 // Cand1 has a better conversion sequence.
3681 HasBetterConversion = true;
3682 break;
3683
3684 case ImplicitConversionSequence::Worse:
3685 // Cand1 can't be better than Cand2.
3686 return false;
3687
3688 case ImplicitConversionSequence::Indistinguishable:
3689 // Do nothing.
3690 break;
3691 }
3692 }
3693
Mike Stump1eb44332009-09-09 15:08:12 +00003694 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003695 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003696 if (HasBetterConversion)
3697 return true;
3698
Mike Stump1eb44332009-09-09 15:08:12 +00003699 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003700 // specialization, or, if not that,
3701 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3702 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3703 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003704
3705 // -- F1 and F2 are function template specializations, and the function
3706 // template for F1 is more specialized than the template for F2
3707 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003708 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00003709 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3710 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003711 if (FunctionTemplateDecl *BetterTemplate
3712 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3713 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor5d7d3752009-09-14 23:02:14 +00003714 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
3715 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003716 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003717
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003718 // -- the context is an initialization by user-defined conversion
3719 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3720 // from the return type of F1 to the destination type (i.e.,
3721 // the type of the entity being initialized) is a better
3722 // conversion sequence than the standard conversion sequence
3723 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00003724 if (Cand1.Function && Cand2.Function &&
3725 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003726 isa<CXXConversionDecl>(Cand2.Function)) {
3727 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3728 Cand2.FinalConversion)) {
3729 case ImplicitConversionSequence::Better:
3730 // Cand1 has a better conversion sequence.
3731 return true;
3732
3733 case ImplicitConversionSequence::Worse:
3734 // Cand1 can't be better than Cand2.
3735 return false;
3736
3737 case ImplicitConversionSequence::Indistinguishable:
3738 // Do nothing
3739 break;
3740 }
3741 }
3742
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003743 return false;
3744}
3745
Mike Stump1eb44332009-09-09 15:08:12 +00003746/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00003747/// within an overload candidate set.
3748///
3749/// \param CandidateSet the set of candidate functions.
3750///
3751/// \param Loc the location of the function name (or operator symbol) for
3752/// which overload resolution occurs.
3753///
Mike Stump1eb44332009-09-09 15:08:12 +00003754/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00003755/// function, Best points to the candidate function found.
3756///
3757/// \returns The result of overload resolution.
Mike Stump1eb44332009-09-09 15:08:12 +00003758Sema::OverloadingResult
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003759Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregore0762c92009-06-19 23:52:42 +00003760 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00003761 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003762 // Find the best viable function.
3763 Best = CandidateSet.end();
3764 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3765 Cand != CandidateSet.end(); ++Cand) {
3766 if (Cand->Viable) {
3767 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3768 Best = Cand;
3769 }
3770 }
3771
3772 // If we didn't find any viable functions, abort.
3773 if (Best == CandidateSet.end())
3774 return OR_No_Viable_Function;
3775
3776 // Make sure that this function is better than every other viable
3777 // function. If not, we have an ambiguity.
3778 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3779 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00003780 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003781 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003782 !isBetterOverloadCandidate(*Best, *Cand)) {
3783 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003784 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003785 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003786 }
Mike Stump1eb44332009-09-09 15:08:12 +00003787
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003788 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003789 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00003790 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003791 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003792 return OR_Deleted;
3793
Douglas Gregore0762c92009-06-19 23:52:42 +00003794 // C++ [basic.def.odr]p2:
3795 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00003796 // when referred to from a potentially-evaluated expression. [Note: this
3797 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00003798 // (clause 13), user-defined conversions (12.3.2), allocation function for
3799 // placement new (5.3.4), as well as non-default initialization (8.5).
3800 if (Best->Function)
3801 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003802 return OR_Success;
3803}
3804
3805/// PrintOverloadCandidates - When overload resolution fails, prints
3806/// diagnostic messages containing the candidates in the candidate
3807/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump1eb44332009-09-09 15:08:12 +00003808void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003809Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00003810 bool OnlyViable) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003811 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3812 LastCand = CandidateSet.end();
3813 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003814 if (Cand->Viable || !OnlyViable) {
3815 if (Cand->Function) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003816 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003817 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003818 // Deleted or "unavailable" function.
3819 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3820 << Cand->Function->isDeleted();
3821 } else {
3822 // Normal function
3823 // FIXME: Give a better reason!
3824 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3825 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003826 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003827 // Desugar the type of the surrogate down to a function type,
3828 // retaining as many typedefs as possible while still showing
3829 // the function type (and, therefore, its parameter types).
3830 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003831 bool isLValueReference = false;
3832 bool isRValueReference = false;
Douglas Gregor621b3932008-11-21 02:54:28 +00003833 bool isPointer = false;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003834 if (const LValueReferenceType *FnTypeRef =
Ted Kremenek6217b802009-07-29 21:53:49 +00003835 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003836 FnType = FnTypeRef->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003837 isLValueReference = true;
3838 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenek6217b802009-07-29 21:53:49 +00003839 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003840 FnType = FnTypeRef->getPointeeType();
3841 isRValueReference = true;
Douglas Gregor621b3932008-11-21 02:54:28 +00003842 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003843 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003844 FnType = FnTypePtr->getPointeeType();
3845 isPointer = true;
3846 }
3847 // Desugar down to a function type.
3848 FnType = QualType(FnType->getAsFunctionType(), 0);
3849 // Reconstruct the pointer/reference as appropriate.
3850 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003851 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3852 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor621b3932008-11-21 02:54:28 +00003853
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003854 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003855 << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003856 } else {
3857 // FIXME: We need to get the identifier in here
Mike Stump390b4cc2009-05-16 07:39:55 +00003858 // FIXME: Do we want the error message to point at the operator?
3859 // (built-ins won't have a location)
Mike Stump1eb44332009-09-09 15:08:12 +00003860 QualType FnType
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003861 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3862 Cand->BuiltinTypes.ParamTypes,
3863 Cand->Conversions.size(),
3864 false, 0);
3865
Chris Lattnerd1625842008-11-24 06:25:27 +00003866 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003867 }
3868 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003869 }
3870}
3871
Douglas Gregor904eed32008-11-10 20:40:00 +00003872/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3873/// an overloaded function (C++ [over.over]), where @p From is an
3874/// expression with overloaded function type and @p ToType is the type
3875/// we're trying to resolve to. For example:
3876///
3877/// @code
3878/// int f(double);
3879/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00003880///
Douglas Gregor904eed32008-11-10 20:40:00 +00003881/// int (*pfd)(double) = f; // selects f(double)
3882/// @endcode
3883///
3884/// This routine returns the resulting FunctionDecl if it could be
3885/// resolved, and NULL otherwise. When @p Complain is true, this
3886/// routine will emit diagnostics if there is an error.
3887FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00003888Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor904eed32008-11-10 20:40:00 +00003889 bool Complain) {
3890 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00003891 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00003892 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00003893 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003894 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00003895 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00003896 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00003897 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00003898 FunctionType = MemTypePtr->getPointeeType();
3899 IsMember = true;
3900 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003901
3902 // We only look at pointers or references to functions.
Douglas Gregor72e771f2009-07-09 17:16:51 +00003903 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor83314aa2009-07-08 20:55:45 +00003904 if (!FunctionType->isFunctionType())
Douglas Gregor904eed32008-11-10 20:40:00 +00003905 return 0;
3906
3907 // Find the actual overloaded function declaration.
3908 OverloadedFunctionDecl *Ovl = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003909
Douglas Gregor904eed32008-11-10 20:40:00 +00003910 // C++ [over.over]p1:
3911 // [...] [Note: any redundant set of parentheses surrounding the
3912 // overloaded function name is ignored (5.1). ]
3913 Expr *OvlExpr = From->IgnoreParens();
3914
3915 // C++ [over.over]p1:
3916 // [...] The overloaded function name can be preceded by the &
3917 // operator.
3918 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3919 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3920 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3921 }
3922
3923 // Try to dig out the overloaded function.
Douglas Gregor83314aa2009-07-08 20:55:45 +00003924 FunctionTemplateDecl *FunctionTemplate = 0;
3925 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00003926 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor83314aa2009-07-08 20:55:45 +00003927 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
3928 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003929
Mike Stump1eb44332009-09-09 15:08:12 +00003930 // If there's no overloaded function declaration or function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00003931 // we're done.
3932 if (!Ovl && !FunctionTemplate)
Douglas Gregor904eed32008-11-10 20:40:00 +00003933 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003934
Douglas Gregor83314aa2009-07-08 20:55:45 +00003935 OverloadIterator Fun;
3936 if (Ovl)
3937 Fun = Ovl;
3938 else
3939 Fun = FunctionTemplate;
Mike Stump1eb44332009-09-09 15:08:12 +00003940
Douglas Gregor904eed32008-11-10 20:40:00 +00003941 // Look through all of the overloaded functions, searching for one
3942 // whose type matches exactly.
Douglas Gregor00aeb522009-07-08 23:33:52 +00003943 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Mike Stump1eb44332009-09-09 15:08:12 +00003944
Douglas Gregor00aeb522009-07-08 23:33:52 +00003945 bool FoundNonTemplateFunction = false;
Douglas Gregor83314aa2009-07-08 20:55:45 +00003946 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregor904eed32008-11-10 20:40:00 +00003947 // C++ [over.over]p3:
3948 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00003949 // targets of type "pointer-to-function" or "reference-to-function."
3950 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00003951 // type "pointer-to-member-function."
3952 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00003953
Mike Stump1eb44332009-09-09 15:08:12 +00003954 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregor83314aa2009-07-08 20:55:45 +00003955 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003956 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00003957 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003958 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00003959 // static when converting to member pointer.
3960 if (Method->isStatic() == IsMember)
3961 continue;
3962 } else if (IsMember)
3963 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003964
Douglas Gregor00aeb522009-07-08 23:33:52 +00003965 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003966 // If the name is a function template, template argument deduction is
3967 // done (14.8.2.2), and if the argument deduction succeeds, the
3968 // resulting template argument list is used to generate a single
3969 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00003970 // overloaded functions considered.
Douglas Gregor83314aa2009-07-08 20:55:45 +00003971 FunctionDecl *Specialization = 0;
3972 TemplateDeductionInfo Info(Context);
3973 if (TemplateDeductionResult Result
3974 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
3975 /*FIXME:*/0, /*FIXME:*/0,
3976 FunctionType, Specialization, Info)) {
3977 // FIXME: make a note of the failed deduction for diagnostics.
3978 (void)Result;
3979 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003980 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00003981 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00003982 Matches.insert(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003983 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor83314aa2009-07-08 20:55:45 +00003984 }
3985 }
Mike Stump1eb44332009-09-09 15:08:12 +00003986
Sebastian Redl33b399a2009-02-04 21:23:32 +00003987 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3988 // Skip non-static functions when converting to pointer, and static
3989 // when converting to member pointer.
3990 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00003991 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00003992 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00003993 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00003994
Douglas Gregore53060f2009-06-25 22:08:12 +00003995 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregor00aeb522009-07-08 23:33:52 +00003996 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003997 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00003998 FoundNonTemplateFunction = true;
3999 }
Mike Stump1eb44332009-09-09 15:08:12 +00004000 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004001 }
4002
Douglas Gregor00aeb522009-07-08 23:33:52 +00004003 // If there were 0 or 1 matches, we're done.
4004 if (Matches.empty())
4005 return 0;
4006 else if (Matches.size() == 1)
4007 return *Matches.begin();
4008
4009 // C++ [over.over]p4:
4010 // If more than one function is selected, [...]
4011 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004012 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004013 if (FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004014 // [...] any function template specializations in the set are
4015 // eliminated if the set also contains a non-template function, [...]
4016 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
Douglas Gregor00aeb522009-07-08 23:33:52 +00004017 if ((*M)->getPrimaryTemplate() == 0)
4018 RemainingMatches.push_back(*M);
4019 } else {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004020 // [...] and any given function template specialization F1 is
4021 // eliminated if the set contains a second function template
4022 // specialization whose function template is more specialized
4023 // than the function template of F1 according to the partial
4024 // ordering rules of 14.5.5.2.
4025
4026 // The algorithm specified above is quadratic. We instead use a
4027 // two-pass algorithm (similar to the one used to identify the
4028 // best viable function in an overload set) that identifies the
4029 // best function template (if it exists).
4030 MatchIter Best = Matches.begin();
4031 MatchIter M = Best, MEnd = Matches.end();
4032 // Find the most specialized function.
4033 for (++M; M != MEnd; ++M)
4034 if (getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4035 (*Best)->getPrimaryTemplate(),
Douglas Gregor8a514912009-09-14 18:39:43 +00004036 TPOC_Other)
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004037 == (*M)->getPrimaryTemplate())
4038 Best = M;
4039
4040 // Determine whether this function template is more specialized
4041 // that all of the others.
4042 bool Ambiguous = false;
4043 for (M = Matches.begin(); M != MEnd; ++M) {
4044 if (M != Best &&
4045 getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4046 (*Best)->getPrimaryTemplate(),
Douglas Gregor8a514912009-09-14 18:39:43 +00004047 TPOC_Other)
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004048 != (*Best)->getPrimaryTemplate()) {
4049 Ambiguous = true;
4050 break;
4051 }
4052 }
4053
4054 // If one function template was more specialized than all of the
4055 // others, return it.
4056 if (!Ambiguous)
4057 return *Best;
4058
4059 // We could not find a most-specialized function template, which
4060 // is equivalent to having a set of function templates with more
4061 // than one such template. So, we place all of the function
4062 // templates into the set of remaining matches and produce a
4063 // diagnostic below. FIXME: we could perform the quadratic
4064 // algorithm here, pruning the result set to limit the number of
4065 // candidates output later.
Douglas Gregord173b202009-09-14 22:02:01 +00004066 RemainingMatches.append(Matches.begin(), Matches.end());
Douglas Gregor00aeb522009-07-08 23:33:52 +00004067 }
Mike Stump1eb44332009-09-09 15:08:12 +00004068
4069 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00004070 // selected function.
4071 if (RemainingMatches.size() == 1)
4072 return RemainingMatches.front();
Mike Stump1eb44332009-09-09 15:08:12 +00004073
Douglas Gregor00aeb522009-07-08 23:33:52 +00004074 // FIXME: We should probably return the same thing that BestViableFunction
4075 // returns (even if we issue the diagnostics here).
4076 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4077 << RemainingMatches[0]->getDeclName();
4078 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4079 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregor904eed32008-11-10 20:40:00 +00004080 return 0;
4081}
4082
Douglas Gregorf6b89692008-11-26 05:54:23 +00004083/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00004084/// (which eventually refers to the declaration Func) and the call
4085/// arguments Args/NumArgs, attempt to resolve the function call down
4086/// to a specific function. If overload resolution succeeds, returns
4087/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00004088/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00004089/// arguments and Fn, and returns NULL.
Douglas Gregorfa047642009-02-04 00:32:51 +00004090FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor17330012009-02-04 15:01:18 +00004091 DeclarationName UnqualifiedName,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004092 bool HasExplicitTemplateArgs,
4093 const TemplateArgument *ExplicitTemplateArgs,
4094 unsigned NumExplicitTemplateArgs,
Douglas Gregor0a396682008-11-26 06:01:48 +00004095 SourceLocation LParenLoc,
4096 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00004097 SourceLocation *CommaLocs,
Douglas Gregorfa047642009-02-04 00:32:51 +00004098 SourceLocation RParenLoc,
Douglas Gregor17330012009-02-04 15:01:18 +00004099 bool &ArgumentDependentLookup) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00004100 OverloadCandidateSet CandidateSet;
Douglas Gregor17330012009-02-04 15:01:18 +00004101
4102 // Add the functions denoted by Callee to the set of candidate
4103 // functions. While we're doing so, track whether argument-dependent
4104 // lookup still applies, per:
4105 //
4106 // C++0x [basic.lookup.argdep]p3:
4107 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4108 // and let Y be the lookup set produced by argument dependent
4109 // lookup (defined as follows). If X contains
4110 //
Mike Stump1eb44332009-09-09 15:08:12 +00004111 // -- a declaration of a class member, or
Douglas Gregor17330012009-02-04 15:01:18 +00004112 //
4113 // -- a block-scope function declaration that is not a
Mike Stump1eb44332009-09-09 15:08:12 +00004114 // using-declaration, or
4115 //
Douglas Gregor17330012009-02-04 15:01:18 +00004116 // -- a declaration that is neither a function or a function
4117 // template
4118 //
Mike Stump1eb44332009-09-09 15:08:12 +00004119 // then Y is empty.
4120 if (OverloadedFunctionDecl *Ovl
Douglas Gregor17330012009-02-04 15:01:18 +00004121 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
4122 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4123 FuncEnd = Ovl->function_end();
4124 Func != FuncEnd; ++Func) {
Douglas Gregore53060f2009-06-25 22:08:12 +00004125 DeclContext *Ctx = 0;
4126 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Func)) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004127 if (HasExplicitTemplateArgs)
4128 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00004129
Douglas Gregore53060f2009-06-25 22:08:12 +00004130 AddOverloadCandidate(FunDecl, Args, NumArgs, CandidateSet);
4131 Ctx = FunDecl->getDeclContext();
4132 } else {
4133 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*Func);
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004134 AddTemplateOverloadCandidate(FunTmpl, HasExplicitTemplateArgs,
4135 ExplicitTemplateArgs,
4136 NumExplicitTemplateArgs,
4137 Args, NumArgs, CandidateSet);
Douglas Gregore53060f2009-06-25 22:08:12 +00004138 Ctx = FunTmpl->getDeclContext();
4139 }
Douglas Gregor17330012009-02-04 15:01:18 +00004140
Douglas Gregore53060f2009-06-25 22:08:12 +00004141
4142 if (Ctx->isRecord() || Ctx->isFunctionOrMethod())
Douglas Gregor17330012009-02-04 15:01:18 +00004143 ArgumentDependentLookup = false;
4144 }
4145 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004146 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregor17330012009-02-04 15:01:18 +00004147 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
4148
4149 if (Func->getDeclContext()->isRecord() ||
4150 Func->getDeclContext()->isFunctionOrMethod())
4151 ArgumentDependentLookup = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004152 } else if (FunctionTemplateDecl *FuncTemplate
Douglas Gregore53060f2009-06-25 22:08:12 +00004153 = dyn_cast_or_null<FunctionTemplateDecl>(Callee)) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004154 AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4155 ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00004156 NumExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004157 Args, NumArgs, CandidateSet);
Douglas Gregore53060f2009-06-25 22:08:12 +00004158
4159 if (FuncTemplate->getDeclContext()->isRecord())
4160 ArgumentDependentLookup = false;
4161 }
Douglas Gregor17330012009-02-04 15:01:18 +00004162
4163 if (Callee)
4164 UnqualifiedName = Callee->getDeclName();
4165
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004166 // FIXME: Pass explicit template arguments through for ADL
Douglas Gregorfa047642009-02-04 00:32:51 +00004167 if (ArgumentDependentLookup)
Douglas Gregor17330012009-02-04 15:01:18 +00004168 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregorfa047642009-02-04 00:32:51 +00004169 CandidateSet);
4170
Douglas Gregorf6b89692008-11-26 05:54:23 +00004171 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004172 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00004173 case OR_Success:
4174 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00004175
4176 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00004177 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00004178 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00004179 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00004180 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4181 break;
4182
4183 case OR_Ambiguous:
4184 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor17330012009-02-04 15:01:18 +00004185 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00004186 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4187 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004188
4189 case OR_Deleted:
4190 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4191 << Best->Function->isDeleted()
4192 << UnqualifiedName
4193 << Fn->getSourceRange();
4194 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4195 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00004196 }
4197
4198 // Overload resolution failed. Destroy all of the subexpressions and
4199 // return NULL.
4200 Fn->Destroy(Context);
4201 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4202 Args[Arg]->Destroy(Context);
4203 return 0;
4204}
4205
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004206/// \brief Create a unary operation that may resolve to an overloaded
4207/// operator.
4208///
4209/// \param OpLoc The location of the operator itself (e.g., '*').
4210///
4211/// \param OpcIn The UnaryOperator::Opcode that describes this
4212/// operator.
4213///
4214/// \param Functions The set of non-member functions that will be
4215/// considered by overload resolution. The caller needs to build this
4216/// set based on the context using, e.g.,
4217/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4218/// set should not contain any member functions; those will be added
4219/// by CreateOverloadedUnaryOp().
4220///
4221/// \param input The input argument.
4222Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4223 unsigned OpcIn,
4224 FunctionSet &Functions,
Mike Stump1eb44332009-09-09 15:08:12 +00004225 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004226 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4227 Expr *Input = (Expr *)input.get();
4228
4229 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4230 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4231 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4232
4233 Expr *Args[2] = { Input, 0 };
4234 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004235
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004236 // For post-increment and post-decrement, add the implicit '0' as
4237 // the second argument, so that we know this is a post-increment or
4238 // post-decrement.
4239 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4240 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00004241 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004242 SourceLocation());
4243 NumArgs = 2;
4244 }
4245
4246 if (Input->isTypeDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004247 OverloadedFunctionDecl *Overloads
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004248 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump1eb44332009-09-09 15:08:12 +00004249 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004250 FuncEnd = Functions.end();
4251 Func != FuncEnd; ++Func)
4252 Overloads->addOverload(*Func);
4253
4254 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4255 OpLoc, false, false);
Mike Stump1eb44332009-09-09 15:08:12 +00004256
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004257 input.release();
4258 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4259 &Args[0], NumArgs,
4260 Context.DependentTy,
4261 OpLoc));
4262 }
4263
4264 // Build an empty overload set.
4265 OverloadCandidateSet CandidateSet;
4266
4267 // Add the candidates from the given function set.
4268 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4269
4270 // Add operator candidates that are member functions.
4271 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4272
4273 // Add builtin operator candidates.
4274 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4275
4276 // Perform overload resolution.
4277 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004278 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004279 case OR_Success: {
4280 // We found a built-in operator or an overloaded operator.
4281 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00004282
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004283 if (FnDecl) {
4284 // We matched an overloaded operator. Build a call to that
4285 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00004286
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004287 // Convert the arguments.
4288 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4289 if (PerformObjectArgumentInitialization(Input, Method))
4290 return ExprError();
4291 } else {
4292 // Convert the arguments.
4293 if (PerformCopyInitialization(Input,
4294 FnDecl->getParamDecl(0)->getType(),
4295 "passing"))
4296 return ExprError();
4297 }
4298
4299 // Determine the result type
4300 QualType ResultTy
4301 = FnDecl->getType()->getAsFunctionType()->getResultType();
4302 ResultTy = ResultTy.getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00004303
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004304 // Build the actual expression node.
4305 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4306 SourceLocation());
4307 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004308
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004309 input.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004310
4311 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlsson2d46eb22009-08-16 04:11:06 +00004312 &Input, 1, ResultTy, OpLoc);
4313 return MaybeBindToTemporary(CE);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004314 } else {
4315 // We matched a built-in operator. Convert the arguments, then
4316 // break out so that we will build the appropriate built-in
4317 // operator node.
4318 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4319 Best->Conversions[0], "passing"))
4320 return ExprError();
4321
4322 break;
4323 }
4324 }
4325
4326 case OR_No_Viable_Function:
4327 // No viable function; fall through to handling this as a
4328 // built-in operator, which will produce an error message for us.
4329 break;
4330
4331 case OR_Ambiguous:
4332 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4333 << UnaryOperator::getOpcodeStr(Opc)
4334 << Input->getSourceRange();
4335 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4336 return ExprError();
4337
4338 case OR_Deleted:
4339 Diag(OpLoc, diag::err_ovl_deleted_oper)
4340 << Best->Function->isDeleted()
4341 << UnaryOperator::getOpcodeStr(Opc)
4342 << Input->getSourceRange();
4343 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4344 return ExprError();
4345 }
4346
4347 // Either we found no viable overloaded operator or we matched a
4348 // built-in operator. In either case, fall through to trying to
4349 // build a built-in operation.
4350 input.release();
4351 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4352}
4353
Douglas Gregor063daf62009-03-13 18:40:31 +00004354/// \brief Create a binary operation that may resolve to an overloaded
4355/// operator.
4356///
4357/// \param OpLoc The location of the operator itself (e.g., '+').
4358///
4359/// \param OpcIn The BinaryOperator::Opcode that describes this
4360/// operator.
4361///
4362/// \param Functions The set of non-member functions that will be
4363/// considered by overload resolution. The caller needs to build this
4364/// set based on the context using, e.g.,
4365/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4366/// set should not contain any member functions; those will be added
4367/// by CreateOverloadedBinOp().
4368///
4369/// \param LHS Left-hand argument.
4370/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00004371Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00004372Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004373 unsigned OpcIn,
Douglas Gregor063daf62009-03-13 18:40:31 +00004374 FunctionSet &Functions,
4375 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00004376 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004377 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00004378
4379 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4380 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4381 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4382
4383 // If either side is type-dependent, create an appropriate dependent
4384 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004385 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor063daf62009-03-13 18:40:31 +00004386 // .* cannot be overloaded.
4387 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004388 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
Douglas Gregor063daf62009-03-13 18:40:31 +00004389 Context.DependentTy, OpLoc));
4390
Mike Stump1eb44332009-09-09 15:08:12 +00004391 OverloadedFunctionDecl *Overloads
Douglas Gregor063daf62009-03-13 18:40:31 +00004392 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump1eb44332009-09-09 15:08:12 +00004393 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004394 FuncEnd = Functions.end();
4395 Func != FuncEnd; ++Func)
4396 Overloads->addOverload(*Func);
4397
4398 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4399 OpLoc, false, false);
Mike Stump1eb44332009-09-09 15:08:12 +00004400
Douglas Gregor063daf62009-03-13 18:40:31 +00004401 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00004402 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00004403 Context.DependentTy,
4404 OpLoc));
4405 }
4406
4407 // If this is the .* operator, which is not overloadable, just
4408 // create a built-in binary operator.
4409 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004410 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00004411
4412 // If this is one of the assignment operators, we only perform
4413 // overload resolution if the left-hand side is a class or
4414 // enumeration type (C++ [expr.ass]p3).
4415 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004416 !Args[0]->getType()->isOverloadableType())
4417 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00004418
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004419 // Build an empty overload set.
4420 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00004421
4422 // Add the candidates from the given function set.
4423 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4424
4425 // Add operator candidates that are member functions.
4426 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4427
4428 // Add builtin operator candidates.
4429 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4430
4431 // Perform overload resolution.
4432 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004433 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004434 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00004435 // We found a built-in operator or an overloaded operator.
4436 FunctionDecl *FnDecl = Best->Function;
4437
4438 if (FnDecl) {
4439 // We matched an overloaded operator. Build a call to that
4440 // operator.
4441
4442 // Convert the arguments.
4443 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004444 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4445 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004446 "passing"))
4447 return ExprError();
4448 } else {
4449 // Convert the arguments.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004450 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004451 "passing") ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004452 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004453 "passing"))
4454 return ExprError();
4455 }
4456
4457 // Determine the result type
4458 QualType ResultTy
4459 = FnDecl->getType()->getAsFunctionType()->getResultType();
4460 ResultTy = ResultTy.getNonReferenceType();
4461
4462 // Build the actual expression node.
4463 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00004464 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00004465 UsualUnaryConversions(FnExpr);
4466
Mike Stump1eb44332009-09-09 15:08:12 +00004467 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlsson2d46eb22009-08-16 04:11:06 +00004468 Args, 2, ResultTy, OpLoc);
4469 return MaybeBindToTemporary(CE);
Douglas Gregor063daf62009-03-13 18:40:31 +00004470 } else {
4471 // We matched a built-in operator. Convert the arguments, then
4472 // break out so that we will build the appropriate built-in
4473 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004474 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor063daf62009-03-13 18:40:31 +00004475 Best->Conversions[0], "passing") ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004476 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor063daf62009-03-13 18:40:31 +00004477 Best->Conversions[1], "passing"))
4478 return ExprError();
4479
4480 break;
4481 }
4482 }
4483
4484 case OR_No_Viable_Function:
Sebastian Redl8593c782009-05-21 11:50:50 +00004485 // For class as left operand for assignment or compound assigment operator
4486 // do not fall through to handling in built-in, but report that no overloaded
4487 // assignment operator found
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004488 if (Args[0]->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00004489 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4490 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004491 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Sebastian Redl8593c782009-05-21 11:50:50 +00004492 return ExprError();
4493 }
Douglas Gregor063daf62009-03-13 18:40:31 +00004494 // No viable function; fall through to handling this as a
4495 // built-in operator, which will produce an error message for us.
4496 break;
4497
4498 case OR_Ambiguous:
4499 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4500 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004501 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor063daf62009-03-13 18:40:31 +00004502 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4503 return ExprError();
4504
4505 case OR_Deleted:
4506 Diag(OpLoc, diag::err_ovl_deleted_oper)
4507 << Best->Function->isDeleted()
4508 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004509 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor063daf62009-03-13 18:40:31 +00004510 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4511 return ExprError();
4512 }
4513
4514 // Either we found no viable overloaded operator or we matched a
4515 // built-in operator. In either case, try to build a built-in
4516 // operation.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004517 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00004518}
4519
Douglas Gregor88a35142008-12-22 05:46:06 +00004520/// BuildCallToMemberFunction - Build a call to a member
4521/// function. MemExpr is the expression that refers to the member
4522/// function (and includes the object parameter), Args/NumArgs are the
4523/// arguments to the function call (not including the object
4524/// parameter). The caller needs to validate that the member
4525/// expression refers to a member function or an overloaded member
4526/// function.
4527Sema::ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00004528Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4529 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00004530 unsigned NumArgs, SourceLocation *CommaLocs,
4531 SourceLocation RParenLoc) {
4532 // Dig out the member expression. This holds both the object
4533 // argument and the member function we're referring to.
4534 MemberExpr *MemExpr = 0;
4535 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4536 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4537 else
4538 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4539 assert(MemExpr && "Building member call without member expression");
4540
4541 // Extract the object argument.
4542 Expr *ObjectArg = MemExpr->getBase();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004543
Douglas Gregor88a35142008-12-22 05:46:06 +00004544 CXXMethodDecl *Method = 0;
Douglas Gregor6b906862009-08-21 00:16:32 +00004545 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4546 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004547 // Add overload candidates
4548 OverloadCandidateSet CandidateSet;
Douglas Gregor6b906862009-08-21 00:16:32 +00004549 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00004550
Douglas Gregordec06662009-08-21 18:42:58 +00004551 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4552 Func != FuncEnd; ++Func) {
4553 if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
Mike Stump1eb44332009-09-09 15:08:12 +00004554 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +00004555 /*SuppressUserConversions=*/false);
4556 else
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00004557 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4558 MemExpr->hasExplicitTemplateArgumentList(),
4559 MemExpr->getTemplateArgs(),
4560 MemExpr->getNumTemplateArgs(),
4561 ObjectArg, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00004562 CandidateSet,
4563 /*SuppressUsedConversions=*/false);
4564 }
Mike Stump1eb44332009-09-09 15:08:12 +00004565
Douglas Gregor88a35142008-12-22 05:46:06 +00004566 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004567 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004568 case OR_Success:
4569 Method = cast<CXXMethodDecl>(Best->Function);
4570 break;
4571
4572 case OR_No_Viable_Function:
Mike Stump1eb44332009-09-09 15:08:12 +00004573 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor88a35142008-12-22 05:46:06 +00004574 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00004575 << DeclName << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00004576 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4577 // FIXME: Leaking incoming expressions!
4578 return true;
4579
4580 case OR_Ambiguous:
Mike Stump1eb44332009-09-09 15:08:12 +00004581 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor88a35142008-12-22 05:46:06 +00004582 diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00004583 << DeclName << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00004584 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4585 // FIXME: Leaking incoming expressions!
4586 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004587
4588 case OR_Deleted:
Mike Stump1eb44332009-09-09 15:08:12 +00004589 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004590 diag::err_ovl_deleted_member_call)
4591 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00004592 << DeclName << MemExprE->getSourceRange();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004593 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4594 // FIXME: Leaking incoming expressions!
4595 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004596 }
4597
4598 FixOverloadedFunctionReference(MemExpr, Method);
4599 } else {
4600 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4601 }
4602
4603 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00004604 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek668bf912009-02-09 20:51:47 +00004605 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00004606 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00004607 Method->getResultType().getNonReferenceType(),
4608 RParenLoc));
4609
4610 // Convert the object argument (for a non-static member function call).
Mike Stump1eb44332009-09-09 15:08:12 +00004611 if (!Method->isStatic() &&
Douglas Gregor88a35142008-12-22 05:46:06 +00004612 PerformObjectArgumentInitialization(ObjectArg, Method))
4613 return true;
4614 MemExpr->setBase(ObjectArg);
4615
4616 // Convert the rest of the arguments
Douglas Gregor72564e72009-02-26 23:50:07 +00004617 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004618 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00004619 RParenLoc))
4620 return true;
4621
Anders Carlssond406bf02009-08-16 01:56:34 +00004622 if (CheckFunctionCall(Method, TheCall.get()))
4623 return true;
Anders Carlsson6f680272009-08-16 03:42:12 +00004624
4625 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor88a35142008-12-22 05:46:06 +00004626}
4627
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004628/// BuildCallToObjectOfClassType - Build a call to an object of class
4629/// type (C++ [over.call.object]), which can end up invoking an
4630/// overloaded function call operator (@c operator()) or performing a
4631/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00004632Sema::ExprResult
4633Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00004634 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004635 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00004636 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004637 SourceLocation RParenLoc) {
4638 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00004639 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004640
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004641 // C++ [over.call.object]p1:
4642 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00004643 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004644 // candidate functions includes at least the function call
4645 // operators of T. The function call operators of T are obtained by
4646 // ordinary lookup of the name operator() in the context of
4647 // (E).operator().
4648 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00004649 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004650 DeclContext::lookup_const_iterator Oper, OperEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004651 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004652 Oper != OperEnd; ++Oper)
Mike Stump1eb44332009-09-09 15:08:12 +00004653 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004654 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004655
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004656 // C++ [over.call.object]p2:
4657 // In addition, for each conversion function declared in T of the
4658 // form
4659 //
4660 // operator conversion-type-id () cv-qualifier;
4661 //
4662 // where cv-qualifier is the same cv-qualification as, or a
4663 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00004664 // denotes the type "pointer to function of (P1,...,Pn) returning
4665 // R", or the type "reference to pointer to function of
4666 // (P1,...,Pn) returning R", or the type "reference to function
4667 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004668 // is also considered as a candidate function. Similarly,
4669 // surrogate call functions are added to the set of candidate
4670 // functions for each conversion function declared in an
4671 // accessible base class provided the function is not hidden
4672 // within T by another intervening declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00004673
Douglas Gregor5842ba92009-08-24 15:23:48 +00004674 if (!RequireCompleteType(SourceLocation(), Object->getType(), 0)) {
4675 // FIXME: Look in base classes for more conversion operators!
Mike Stump1eb44332009-09-09 15:08:12 +00004676 OverloadedFunctionDecl *Conversions
Douglas Gregor5842ba92009-08-24 15:23:48 +00004677 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00004678 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor5842ba92009-08-24 15:23:48 +00004679 Func = Conversions->function_begin(),
4680 FuncEnd = Conversions->function_end();
4681 Func != FuncEnd; ++Func) {
4682 CXXConversionDecl *Conv;
4683 FunctionTemplateDecl *ConvTemplate;
4684 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004685
Douglas Gregor5842ba92009-08-24 15:23:48 +00004686 // Skip over templated conversion functions; they aren't
4687 // surrogates.
4688 if (ConvTemplate)
4689 continue;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004690
Douglas Gregor5842ba92009-08-24 15:23:48 +00004691 // Strip the reference type (if any) and then the pointer type (if
4692 // any) to get down to what might be a function type.
4693 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4694 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4695 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004696
Douglas Gregor5842ba92009-08-24 15:23:48 +00004697 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
4698 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4699 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004700 }
Mike Stump1eb44332009-09-09 15:08:12 +00004701
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004702 // Perform overload resolution.
4703 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004704 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004705 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004706 // Overload resolution succeeded; we'll build the appropriate call
4707 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004708 break;
4709
4710 case OR_No_Viable_Function:
Mike Stump1eb44332009-09-09 15:08:12 +00004711 Diag(Object->getSourceRange().getBegin(),
Sebastian Redle4c452c2008-11-22 13:44:36 +00004712 diag::err_ovl_no_viable_object_call)
Chris Lattner4330d652009-02-17 07:29:20 +00004713 << Object->getType() << Object->getSourceRange();
Sebastian Redle4c452c2008-11-22 13:44:36 +00004714 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004715 break;
4716
4717 case OR_Ambiguous:
4718 Diag(Object->getSourceRange().getBegin(),
4719 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00004720 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004721 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4722 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004723
4724 case OR_Deleted:
4725 Diag(Object->getSourceRange().getBegin(),
4726 diag::err_ovl_deleted_object_call)
4727 << Best->Function->isDeleted()
4728 << Object->getType() << Object->getSourceRange();
4729 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4730 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004731 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004732
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004733 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004734 // We had an error; delete all of the subexpressions and return
4735 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004736 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004737 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00004738 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004739 return true;
4740 }
4741
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004742 if (Best->Function == 0) {
4743 // Since there is no function declaration, this is one of the
4744 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00004745 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004746 = cast<CXXConversionDecl>(
4747 Best->Conversions[0].UserDefined.ConversionFunction);
4748
4749 // We selected one of the surrogate functions that converts the
4750 // object parameter to a function pointer. Perform the conversion
4751 // on the object argument, then let ActOnCallExpr finish the job.
4752 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl0eb23302009-01-19 00:08:26 +00004753 ImpCastExprToType(Object,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004754 Conv->getConversionType().getNonReferenceType(),
Anders Carlsson3503d042009-07-31 01:23:52 +00004755 CastExpr::CK_Unknown,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004756 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00004757 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4758 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4759 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004760 }
4761
4762 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4763 // that calls this method, using Object for the implicit object
4764 // parameter and passing along the remaining arguments.
4765 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor72564e72009-02-26 23:50:07 +00004766 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004767
4768 unsigned NumArgsInProto = Proto->getNumArgs();
4769 unsigned NumArgsToCheck = NumArgs;
4770
4771 // Build the full argument list for the method call (the
4772 // implicit object parameter is placed at the beginning of the
4773 // list).
4774 Expr **MethodArgs;
4775 if (NumArgs < NumArgsInProto) {
4776 NumArgsToCheck = NumArgsInProto;
4777 MethodArgs = new Expr*[NumArgsInProto + 1];
4778 } else {
4779 MethodArgs = new Expr*[NumArgs + 1];
4780 }
4781 MethodArgs[0] = Object;
4782 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4783 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00004784
4785 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004786 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004787 UsualUnaryConversions(NewFn);
4788
4789 // Once we've built TheCall, all of the expressions are properly
4790 // owned.
4791 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00004792 ExprOwningPtr<CXXOperatorCallExpr>
4793 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00004794 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004795 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004796 delete [] MethodArgs;
4797
Douglas Gregor518fda12009-01-13 05:10:00 +00004798 // We may have default arguments. If so, we need to allocate more
4799 // slots in the call for them.
4800 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00004801 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00004802 else if (NumArgs > NumArgsInProto)
4803 NumArgsToCheck = NumArgsInProto;
4804
Chris Lattner312531a2009-04-12 08:11:20 +00004805 bool IsError = false;
4806
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004807 // Initialize the implicit object parameter.
Chris Lattner312531a2009-04-12 08:11:20 +00004808 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004809 TheCall->setArg(0, Object);
4810
Chris Lattner312531a2009-04-12 08:11:20 +00004811
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004812 // Check the argument types.
4813 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004814 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00004815 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004816 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00004817
Douglas Gregor518fda12009-01-13 05:10:00 +00004818 // Pass the argument.
4819 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner312531a2009-04-12 08:11:20 +00004820 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor518fda12009-01-13 05:10:00 +00004821 } else {
Anders Carlssonf1480ee2009-08-14 18:30:22 +00004822 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregor518fda12009-01-13 05:10:00 +00004823 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004824
4825 TheCall->setArg(i + 1, Arg);
4826 }
4827
4828 // If this is a variadic call, handle args passed through "...".
4829 if (Proto->isVariadic()) {
4830 // Promote the arguments (C99 6.5.2.2p7).
4831 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4832 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00004833 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004834 TheCall->setArg(i + 1, Arg);
4835 }
4836 }
4837
Chris Lattner312531a2009-04-12 08:11:20 +00004838 if (IsError) return true;
4839
Anders Carlssond406bf02009-08-16 01:56:34 +00004840 if (CheckFunctionCall(Method, TheCall.get()))
4841 return true;
4842
Anders Carlssona303f9e2009-08-16 03:53:54 +00004843 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004844}
4845
Douglas Gregor8ba10742008-11-20 16:27:02 +00004846/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00004847/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00004848/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004849Sema::OwningExprResult
4850Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
4851 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00004852 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00004853
Douglas Gregor8ba10742008-11-20 16:27:02 +00004854 // C++ [over.ref]p1:
4855 //
4856 // [...] An expression x->m is interpreted as (x.operator->())->m
4857 // for a class object x of type T if T::operator->() exists and if
4858 // the operator is selected as the best match function by the
4859 // overload resolution mechanism (13.3).
4860 // FIXME: look in base classes.
4861 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4862 OverloadCandidateSet CandidateSet;
Ted Kremenek6217b802009-07-29 21:53:49 +00004863 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004864
Anders Carlssone30572a2009-09-10 23:18:36 +00004865 LookupResult R = LookupQualifiedName(BaseRecord->getDecl(), OpName,
4866 LookupOrdinaryName);
4867
4868 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
4869 Oper != OperEnd; ++Oper)
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004870 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00004871 /*SuppressUserConversions=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00004872
4873 // Perform overload resolution.
4874 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004875 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00004876 case OR_Success:
4877 // Overload resolution succeeded; we'll build the call below.
4878 break;
4879
4880 case OR_No_Viable_Function:
4881 if (CandidateSet.empty())
4882 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004883 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004884 else
4885 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004886 << "operator->" << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004887 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004888 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004889
4890 case OR_Ambiguous:
4891 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00004892 << "->" << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004893 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004894 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004895
4896 case OR_Deleted:
4897 Diag(OpLoc, diag::err_ovl_deleted_oper)
4898 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00004899 << "->" << Base->getSourceRange();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004900 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004901 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004902 }
4903
4904 // Convert the object parameter.
4905 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00004906 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004907 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00004908
4909 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004910 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004911
4912 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004913 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4914 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00004915 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004916 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor8ba10742008-11-20 16:27:02 +00004917 Method->getResultType().getNonReferenceType(),
4918 OpLoc);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004919 return Owned(Base);
Douglas Gregor8ba10742008-11-20 16:27:02 +00004920}
4921
Douglas Gregor904eed32008-11-10 20:40:00 +00004922/// FixOverloadedFunctionReference - E is an expression that refers to
4923/// a C++ overloaded function (possibly with some parentheses and
4924/// perhaps a '&' around it). We have resolved the overloaded function
4925/// to the function declaration Fn, so patch up the expression E to
4926/// refer (possibly indirectly) to Fn.
4927void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4928 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4929 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4930 E->setType(PE->getSubExpr()->getType());
4931 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004932 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00004933 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00004934 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4935 if (Method->isStatic()) {
4936 // Do nothing: static member functions aren't any different
4937 // from non-member functions.
Mike Stump1eb44332009-09-09 15:08:12 +00004938 } else if (QualifiedDeclRefExpr *DRE
Douglas Gregorb86b0572009-02-11 01:18:59 +00004939 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4940 // We have taken the address of a pointer to member
4941 // function. Perform the computation here so that we get the
4942 // appropriate pointer to member type.
4943 DRE->setDecl(Fn);
4944 DRE->setType(Fn->getType());
4945 QualType ClassType
4946 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
Mike Stump1eb44332009-09-09 15:08:12 +00004947 E->setType(Context.getMemberPointerType(Fn->getType(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00004948 ClassType.getTypePtr()));
4949 return;
4950 }
4951 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004952 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregora35284b2009-02-11 00:19:33 +00004953 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor904eed32008-11-10 20:40:00 +00004954 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00004955 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004956 isa<FunctionTemplateDecl>(DR->getDecl())) &&
Douglas Gregor83314aa2009-07-08 20:55:45 +00004957 "Expected overloaded function or function template");
Douglas Gregor904eed32008-11-10 20:40:00 +00004958 DR->setDecl(Fn);
4959 E->setType(Fn->getType());
Douglas Gregor88a35142008-12-22 05:46:06 +00004960 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4961 MemExpr->setMemberDecl(Fn);
4962 E->setType(Fn->getType());
Douglas Gregor904eed32008-11-10 20:40:00 +00004963 } else {
4964 assert(false && "Invalid reference to overloaded function");
4965 }
4966}
4967
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004968} // end namespace clang