blob: 2acc4e455924fe913b70aa4c697aa50e017c7387 [file] [log] [blame]
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor94b1dd22008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000022#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000023#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000025#include "llvm/Support/Compiler.h"
26#include <algorithm>
Torok Edwinf42e4a62009-08-24 13:25:12 +000027#include <cstdio>
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000028
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
41 ICC_Qualification_Adjustment,
42 ICC_Promotion,
43 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000044 ICC_Promotion,
45 ICC_Conversion,
46 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000047 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000052 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000053 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000054 ICC_Conversion
55 };
56 return Category[(int)Kind];
57}
58
59/// GetConversionRank - Retrieve the implicit conversion rank
60/// corresponding to the given implicit conversion kind.
61ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
62 static const ImplicitConversionRank
63 Rank[(int)ICK_Num_Conversion_Kinds] = {
64 ICR_Exact_Match,
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Promotion,
70 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000071 ICR_Promotion,
72 ICR_Conversion,
73 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000074 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000079 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000080 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000081 ICR_Conversion
82 };
83 return Rank[(int)Kind];
84}
85
86/// GetImplicitConversionName - Return the name of this kind of
87/// implicit conversion.
88const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
89 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
90 "No conversion",
91 "Lvalue-to-rvalue",
92 "Array-to-pointer",
93 "Function-to-pointer",
94 "Qualification",
95 "Integral promotion",
96 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +000097 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000098 "Integral conversion",
99 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000100 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000101 "Floating-integral conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000102 "Complex-real conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000103 "Pointer conversion",
104 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000105 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000106 "Compatible-types conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000107 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000108 };
109 return Name[Kind];
110}
111
Douglas Gregor60d62c22008-10-31 16:23:19 +0000112/// StandardConversionSequence - Set the standard conversion
113/// sequence to the identity conversion.
114void StandardConversionSequence::setAsIdentityConversion() {
115 First = ICK_Identity;
116 Second = ICK_Identity;
117 Third = ICK_Identity;
118 Deprecated = false;
119 ReferenceBinding = false;
120 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000121 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000122 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000123}
124
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000125/// getRank - Retrieve the rank of this standard conversion sequence
126/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
127/// implicit conversions.
128ImplicitConversionRank StandardConversionSequence::getRank() const {
129 ImplicitConversionRank Rank = ICR_Exact_Match;
130 if (GetConversionRank(First) > Rank)
131 Rank = GetConversionRank(First);
132 if (GetConversionRank(Second) > Rank)
133 Rank = GetConversionRank(Second);
134 if (GetConversionRank(Third) > Rank)
135 Rank = GetConversionRank(Third);
136 return Rank;
137}
138
139/// isPointerConversionToBool - Determines whether this conversion is
140/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000141/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000142/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000143bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000144 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
145 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
146
147 // Note that FromType has not necessarily been transformed by the
148 // array-to-pointer or function-to-pointer implicit conversions, so
149 // check for their presence as well as checking whether FromType is
150 // a pointer.
151 if (ToType->isBooleanType() &&
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000152 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000153 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154 return true;
155
156 return false;
157}
158
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000159/// isPointerConversionToVoidPointer - Determines whether this
160/// conversion is a conversion of a pointer to a void pointer. This is
161/// used as part of the ranking of standard conversion sequences (C++
162/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000163bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000166 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
167 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
168
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
174
175 if (Second == ICK_Pointer_Conversion)
Ted Kremenek6217b802009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
185 bool PrintedSomething = false;
186 if (First != ICK_Identity) {
187 fprintf(stderr, "%s", GetImplicitConversionName(First));
188 PrintedSomething = true;
189 }
190
191 if (Second != ICK_Identity) {
192 if (PrintedSomething) {
193 fprintf(stderr, " -> ");
194 }
195 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor225c41e2008-11-03 19:09:14 +0000196
197 if (CopyConstructor) {
198 fprintf(stderr, " (by copy constructor)");
199 } else if (DirectBinding) {
200 fprintf(stderr, " (direct reference binding)");
201 } else if (ReferenceBinding) {
202 fprintf(stderr, " (reference binding)");
203 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000204 PrintedSomething = true;
205 }
206
207 if (Third != ICK_Identity) {
208 if (PrintedSomething) {
209 fprintf(stderr, " -> ");
210 }
211 fprintf(stderr, "%s", GetImplicitConversionName(Third));
212 PrintedSomething = true;
213 }
214
215 if (!PrintedSomething) {
216 fprintf(stderr, "No conversions required");
217 }
218}
219
220/// DebugPrint - Print this user-defined conversion sequence to standard
221/// error. Useful for debugging overloading issues.
222void UserDefinedConversionSequence::DebugPrint() const {
223 if (Before.First || Before.Second || Before.Third) {
224 Before.DebugPrint();
225 fprintf(stderr, " -> ");
226 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000227 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000228 if (After.First || After.Second || After.Third) {
229 fprintf(stderr, " -> ");
230 After.DebugPrint();
231 }
232}
233
234/// DebugPrint - Print this implicit conversion sequence to standard
235/// error. Useful for debugging overloading issues.
236void ImplicitConversionSequence::DebugPrint() const {
237 switch (ConversionKind) {
238 case StandardConversion:
239 fprintf(stderr, "Standard conversion: ");
240 Standard.DebugPrint();
241 break;
242 case UserDefinedConversion:
243 fprintf(stderr, "User-defined conversion: ");
244 UserDefined.DebugPrint();
245 break;
246 case EllipsisConversion:
247 fprintf(stderr, "Ellipsis conversion");
248 break;
249 case BadConversion:
250 fprintf(stderr, "Bad conversion");
251 break;
252 }
253
254 fprintf(stderr, "\n");
255}
256
257// IsOverload - Determine whether the given New declaration is an
258// overload of the Old declaration. This routine returns false if New
259// and Old cannot be overloaded, e.g., if they are functions with the
260// same signature (C++ 1.3.10) or if the Old declaration isn't a
261// function (or overload set). When it does return false and Old is an
262// OverloadedFunctionDecl, MatchedDecl will be set to point to the
Mike Stump1eb44332009-09-09 15:08:12 +0000263// FunctionDecl that New cannot be overloaded with.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000264//
265// Example: Given the following input:
266//
267// void f(int, float); // #1
268// void f(int, int); // #2
269// int f(int, int); // #3
270//
271// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000272// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000273//
274// When we process #2, Old is a FunctionDecl for #1. By comparing the
275// parameter types, we see that #1 and #2 are overloaded (since they
276// have different signatures), so this routine returns false;
277// MatchedDecl is unchanged.
278//
279// When we process #3, Old is an OverloadedFunctionDecl containing #1
280// and #2. We compare the signatures of #3 to #1 (they're overloaded,
281// so we do nothing) and then #3 to #2. Since the signatures of #3 and
282// #2 are identical (return types of functions are not part of the
283// signature), IsOverload returns false and MatchedDecl will be set to
284// point to the FunctionDecl for #2.
285bool
Mike Stump1eb44332009-09-09 15:08:12 +0000286Sema::IsOverload(FunctionDecl *New, Decl* OldD,
287 OverloadedFunctionDecl::function_iterator& MatchedDecl) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000288 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
289 // Is this new function an overload of every function in the
290 // overload set?
291 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
292 FuncEnd = Ovl->function_end();
293 for (; Func != FuncEnd; ++Func) {
294 if (!IsOverload(New, *Func, MatchedDecl)) {
295 MatchedDecl = Func;
296 return false;
297 }
298 }
299
300 // This function overloads every function in the overload set.
301 return true;
Douglas Gregore53060f2009-06-25 22:08:12 +0000302 } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
303 return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
304 else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000305 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +0000306 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
307
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000308 // C++ [temp.fct]p2:
309 // A function template can be overloaded with other function templates
310 // and with normal (non-template) functions.
311 if ((OldTemplate == 0) != (NewTemplate == 0))
312 return true;
313
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000314 // Is the function New an overload of the function Old?
315 QualType OldQType = Context.getCanonicalType(Old->getType());
316 QualType NewQType = Context.getCanonicalType(New->getType());
317
318 // Compare the signatures (C++ 1.3.10) of the two functions to
319 // determine whether they are overloads. If we find any mismatch
320 // in the signature, they are overloads.
321
322 // If either of these functions is a K&R-style function (no
323 // prototype), then we consider them to have matching signatures.
Douglas Gregor72564e72009-02-26 23:50:07 +0000324 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
325 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000326 return false;
327
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000328 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
329 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000330
331 // The signature of a function includes the types of its
332 // parameters (C++ 1.3.10), which includes the presence or absence
333 // of the ellipsis; see C++ DR 357).
334 if (OldQType != NewQType &&
335 (OldType->getNumArgs() != NewType->getNumArgs() ||
336 OldType->isVariadic() != NewType->isVariadic() ||
337 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
338 NewType->arg_type_begin())))
339 return true;
340
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000341 // C++ [temp.over.link]p4:
Mike Stump1eb44332009-09-09 15:08:12 +0000342 // The signature of a function template consists of its function
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000343 // signature, its return type and its template parameter list. The names
344 // of the template parameters are significant only for establishing the
Mike Stump1eb44332009-09-09 15:08:12 +0000345 // relationship between the template parameters and the rest of the
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000346 // signature.
347 //
348 // We check the return type and template parameter lists for function
349 // templates first; the remaining checks follow.
350 if (NewTemplate &&
Mike Stump1eb44332009-09-09 15:08:12 +0000351 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
352 OldTemplate->getTemplateParameters(),
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000353 false, false, SourceLocation()) ||
354 OldType->getResultType() != NewType->getResultType()))
355 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000357 // If the function is a class member, its signature includes the
358 // cv-qualifiers (if any) on the function itself.
359 //
360 // As part of this, also check whether one of the member functions
361 // is static, in which case they are not overloads (C++
362 // 13.1p2). While not part of the definition of the signature,
363 // this check is important to determine whether these functions
364 // can be overloaded.
365 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
366 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Mike Stump1eb44332009-09-09 15:08:12 +0000367 if (OldMethod && NewMethod &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000368 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor1ca50c32008-11-21 15:36:28 +0000369 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000370 return true;
371
372 // The signatures match; this is not an overload.
373 return false;
374 } else {
375 // (C++ 13p1):
376 // Only function declarations can be overloaded; object and type
377 // declarations cannot be overloaded.
378 return false;
379 }
380}
381
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000382/// TryImplicitConversion - Attempt to perform an implicit conversion
383/// from the given expression (Expr) to the given type (ToType). This
384/// function returns an implicit conversion sequence that can be used
385/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000386///
387/// void f(float f);
388/// void g(int i) { f(i); }
389///
390/// this routine would produce an implicit conversion sequence to
391/// describe the initialization of f from i, which will be a standard
392/// conversion sequence containing an lvalue-to-rvalue conversion (C++
393/// 4.1) followed by a floating-integral conversion (C++ 4.9).
394//
395/// Note that this routine only determines how the conversion can be
396/// performed; it does not actually perform the conversion. As such,
397/// it will not produce any diagnostics if no conversion is available,
398/// but will instead return an implicit conversion sequence of kind
399/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000400///
401/// If @p SuppressUserConversions, then user-defined conversions are
402/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000403/// If @p AllowExplicit, then explicit user-defined conversions are
404/// permitted.
Sebastian Redle2b68332009-04-12 17:16:29 +0000405/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
406/// no matter its actual lvalueness.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000407ImplicitConversionSequence
Anders Carlsson2974b5c2009-08-27 17:14:02 +0000408Sema::TryImplicitConversion(Expr* From, QualType ToType,
409 bool SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +0000410 bool AllowExplicit, bool ForceRValue,
Mike Stump1eb44332009-09-09 15:08:12 +0000411 bool InOverloadResolution) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000412 ImplicitConversionSequence ICS;
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +0000413 OverloadCandidateSet Conversions;
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000414 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson08972922009-08-28 15:33:32 +0000415 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor60d62c22008-10-31 16:23:19 +0000416 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000417 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000418 (UserDefResult = IsUserDefinedConversion(From, ToType,
419 ICS.UserDefined,
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +0000420 Conversions,
Sebastian Redle2b68332009-04-12 17:16:29 +0000421 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000422 ForceRValue)) == OR_Success) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000423 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000424 // C++ [over.ics.user]p4:
425 // A conversion of an expression of class type to the same class
426 // type is given Exact Match rank, and a conversion of an
427 // expression of class type to a base class of that type is
428 // given Conversion rank, in spite of the fact that a copy
429 // constructor (i.e., a user-defined conversion function) is
430 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000431 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000432 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000433 QualType FromCanon
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000434 = Context.getCanonicalType(From->getType().getUnqualifiedType());
435 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
436 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000437 // Turn this into a "standard" conversion sequence, so that it
438 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000439 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
440 ICS.Standard.setAsIdentityConversion();
441 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
442 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000443 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000444 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000445 ICS.Standard.Second = ICK_Derived_To_Base;
446 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000447 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000448
449 // C++ [over.best.ics]p4:
450 // However, when considering the argument of a user-defined
451 // conversion function that is a candidate by 13.3.1.3 when
452 // invoked for the copying of the temporary in the second step
453 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
454 // 13.3.1.6 in all cases, only standard conversion sequences and
455 // ellipsis conversion sequences are allowed.
456 if (SuppressUserConversions &&
457 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
458 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000459 } else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000460 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000461 if (UserDefResult == OR_Ambiguous) {
462 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
463 Cand != Conversions.end(); ++Cand)
464 ICS.ConversionFunctionSet.push_back(Cand->Function);
465 }
466 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000467
468 return ICS;
469}
470
471/// IsStandardConversion - Determines whether there is a standard
472/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
473/// expression From to the type ToType. Standard conversion sequences
474/// only consider non-class types; for conversions that involve class
475/// types, use TryImplicitConversion. If a conversion exists, SCS will
476/// contain the standard conversion sequence required to perform this
477/// conversion and this routine will return true. Otherwise, this
478/// routine will return false and the value of SCS is unspecified.
Mike Stump1eb44332009-09-09 15:08:12 +0000479bool
480Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000481 bool InOverloadResolution,
Mike Stump1eb44332009-09-09 15:08:12 +0000482 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000483 QualType FromType = From->getType();
484
Douglas Gregor60d62c22008-10-31 16:23:19 +0000485 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000486 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000487 SCS.Deprecated = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000488 SCS.IncompatibleObjC = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000489 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000490 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000491
Douglas Gregorf9201e02009-02-11 23:02:49 +0000492 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000493 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000494 if (FromType->isRecordType() || ToType->isRecordType()) {
495 if (getLangOptions().CPlusPlus)
496 return false;
497
Mike Stump1eb44332009-09-09 15:08:12 +0000498 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000499 }
500
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000501 // The first conversion can be an lvalue-to-rvalue conversion,
502 // array-to-pointer conversion, or function-to-pointer conversion
503 // (C++ 4p1).
504
Mike Stump1eb44332009-09-09 15:08:12 +0000505 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000506 // An lvalue (3.10) of a non-function, non-array type T can be
507 // converted to an rvalue.
508 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000509 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000510 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000511 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000512 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000513
514 // If T is a non-class type, the type of the rvalue is the
515 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000516 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
517 // just strip the qualifiers because they don't matter.
518
519 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregor60d62c22008-10-31 16:23:19 +0000520 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000521 } else if (FromType->isArrayType()) {
522 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000523 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000524
525 // An lvalue or rvalue of type "array of N T" or "array of unknown
526 // bound of T" can be converted to an rvalue of type "pointer to
527 // T" (C++ 4.2p1).
528 FromType = Context.getArrayDecayedType(FromType);
529
530 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
531 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000532 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000533
534 // For the purpose of ranking in overload resolution
535 // (13.3.3.1.1), this conversion is considered an
536 // array-to-pointer conversion followed by a qualification
537 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000538 SCS.Second = ICK_Identity;
539 SCS.Third = ICK_Qualification;
540 SCS.ToTypePtr = ToType.getAsOpaquePtr();
541 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000542 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000543 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
544 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000545 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000546
547 // An lvalue of function type T can be converted to an rvalue of
548 // type "pointer to T." The result is a pointer to the
549 // function. (C++ 4.3p1).
550 FromType = Context.getPointerType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000551 } else if (FunctionDecl *Fn
Douglas Gregor904eed32008-11-10 20:40:00 +0000552 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000553 // Address of overloaded function (C++ [over.over]).
Douglas Gregor904eed32008-11-10 20:40:00 +0000554 SCS.First = ICK_Function_To_Pointer;
555
556 // We were able to resolve the address of the overloaded function,
557 // so we can convert to the type of that function.
558 FromType = Fn->getType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000559 if (ToType->isLValueReferenceType())
560 FromType = Context.getLValueReferenceType(FromType);
561 else if (ToType->isRValueReferenceType())
562 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000563 else if (ToType->isMemberPointerType()) {
564 // Resolve address only succeeds if both sides are member pointers,
565 // but it doesn't have to be the same class. See DR 247.
566 // Note that this means that the type of &Derived::fn can be
567 // Ret (Base::*)(Args) if the fn overload actually found is from the
568 // base class, even if it was brought into the derived class via a
569 // using declaration. The standard isn't clear on this issue at all.
570 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
571 FromType = Context.getMemberPointerType(FromType,
572 Context.getTypeDeclType(M->getParent()).getTypePtr());
573 } else
Douglas Gregor904eed32008-11-10 20:40:00 +0000574 FromType = Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000575 } else {
576 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000577 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000578 }
579
580 // The second conversion can be an integral promotion, floating
581 // point promotion, integral conversion, floating point conversion,
582 // floating-integral conversion, pointer conversion,
583 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000584 // For overloading in C, this can also be a "compatible-type"
585 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000586 bool IncompatibleObjC = false;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000587 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000588 // The unqualified versions of the types are the same: there's no
589 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000590 SCS.Second = ICK_Identity;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000591 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000592 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000593 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000594 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000595 } else if (IsFloatingPointPromotion(FromType, ToType)) {
596 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000597 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000598 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000599 } else if (IsComplexPromotion(FromType, ToType)) {
600 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000601 SCS.Second = ICK_Complex_Promotion;
602 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000603 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000604 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000605 // Integral conversions (C++ 4.7).
606 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000607 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000608 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000609 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
610 // Floating point conversions (C++ 4.8).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000611 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000612 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000613 } else if (FromType->isComplexType() && ToType->isComplexType()) {
614 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000615 SCS.Second = ICK_Complex_Conversion;
616 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000617 } else if ((FromType->isFloatingType() &&
618 ToType->isIntegralType() && (!ToType->isBooleanType() &&
619 !ToType->isEnumeralType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000620 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000621 ToType->isFloatingType())) {
622 // Floating-integral conversions (C++ 4.9).
623 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000624 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000625 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000626 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
627 (ToType->isComplexType() && FromType->isArithmeticType())) {
628 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000629 SCS.Second = ICK_Complex_Real;
630 FromType = ToType.getUnqualifiedType();
Anders Carlsson08972922009-08-28 15:33:32 +0000631 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
632 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000633 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000634 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000635 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregorce940492009-09-25 04:25:58 +0000636 } else if (IsMemberPointerConversion(From, FromType, ToType,
637 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000638 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000639 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000640 } else if (ToType->isBooleanType() &&
641 (FromType->isArithmeticType() ||
642 FromType->isEnumeralType() ||
643 FromType->isPointerType() ||
644 FromType->isBlockPointerType() ||
645 FromType->isMemberPointerType() ||
646 FromType->isNullPtrType())) {
647 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000648 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000649 FromType = Context.BoolTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000650 } else if (!getLangOptions().CPlusPlus &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000651 Context.typesAreCompatible(ToType, FromType)) {
652 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000653 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000654 } else {
655 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000656 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000657 }
658
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000659 QualType CanonFrom;
660 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000661 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000662 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000663 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000664 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000665 CanonFrom = Context.getCanonicalType(FromType);
666 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000667 } else {
668 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000669 SCS.Third = ICK_Identity;
670
Mike Stump1eb44332009-09-09 15:08:12 +0000671 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +0000672 // [...] Any difference in top-level cv-qualification is
673 // subsumed by the initialization itself and does not constitute
674 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000675 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000676 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000677 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000678 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
679 FromType = ToType;
680 CanonFrom = CanonTo;
681 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000682 }
683
684 // If we have not converted the argument type to the parameter type,
685 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000686 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000687 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000688
Douglas Gregor60d62c22008-10-31 16:23:19 +0000689 SCS.ToTypePtr = FromType.getAsOpaquePtr();
690 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000691}
692
693/// IsIntegralPromotion - Determines whether the conversion from the
694/// expression From (whose potentially-adjusted type is FromType) to
695/// ToType is an integral promotion (C++ 4.5). If so, returns true and
696/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000697bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000698 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000699 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000700 if (!To) {
701 return false;
702 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000703
704 // An rvalue of type char, signed char, unsigned char, short int, or
705 // unsigned short int can be converted to an rvalue of type int if
706 // int can represent all the values of the source type; otherwise,
707 // the source rvalue can be converted to an rvalue of type unsigned
708 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000709 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000710 if (// We can promote any signed, promotable integer type to an int
711 (FromType->isSignedIntegerType() ||
712 // We can promote any unsigned integer type whose size is
713 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +0000714 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000715 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000716 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000717 }
718
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000719 return To->getKind() == BuiltinType::UInt;
720 }
721
722 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
723 // can be converted to an rvalue of the first of the following types
724 // that can represent all the values of its underlying type: int,
725 // unsigned int, long, or unsigned long (C++ 4.5p2).
726 if ((FromType->isEnumeralType() || FromType->isWideCharType())
727 && ToType->isIntegerType()) {
728 // Determine whether the type we're converting from is signed or
729 // unsigned.
730 bool FromIsSigned;
731 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall183700f2009-09-21 23:43:11 +0000732 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000733 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
734 FromIsSigned = UnderlyingType->isSignedIntegerType();
735 } else {
736 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
737 FromIsSigned = true;
738 }
739
740 // The types we'll try to promote to, in the appropriate
741 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +0000742 QualType PromoteTypes[6] = {
743 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000744 Context.LongTy, Context.UnsignedLongTy ,
745 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000746 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000747 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000748 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
749 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +0000750 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000751 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
752 // We found the type that we can promote to. If this is the
753 // type we wanted, we have a promotion. Otherwise, no
754 // promotion.
Sebastian Redl07779722008-10-31 14:43:28 +0000755 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000756 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
757 }
758 }
759 }
760
761 // An rvalue for an integral bit-field (9.6) can be converted to an
762 // rvalue of type int if int can represent all the values of the
763 // bit-field; otherwise, it can be converted to unsigned int if
764 // unsigned int can represent all the values of the bit-field. If
765 // the bit-field is larger yet, no integral promotion applies to
766 // it. If the bit-field has an enumerated type, it is treated as any
767 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +0000768 // FIXME: We should delay checking of bit-fields until we actually perform the
769 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000770 using llvm::APSInt;
771 if (From)
772 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +0000773 APSInt BitWidth;
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000774 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
775 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
776 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
777 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Douglas Gregor86f19402008-12-20 23:49:58 +0000779 // Are we promoting to an int from a bitfield that fits in an int?
780 if (BitWidth < ToSize ||
781 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
782 return To->getKind() == BuiltinType::Int;
783 }
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Douglas Gregor86f19402008-12-20 23:49:58 +0000785 // Are we promoting to an unsigned int from an unsigned bitfield
786 // that fits into an unsigned int?
787 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
788 return To->getKind() == BuiltinType::UInt;
789 }
Mike Stump1eb44332009-09-09 15:08:12 +0000790
Douglas Gregor86f19402008-12-20 23:49:58 +0000791 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000792 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000793 }
Mike Stump1eb44332009-09-09 15:08:12 +0000794
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000795 // An rvalue of type bool can be converted to an rvalue of type int,
796 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000797 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000798 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000799 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000800
801 return false;
802}
803
804/// IsFloatingPointPromotion - Determines whether the conversion from
805/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
806/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000807bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000808 /// An rvalue of type float can be converted to an rvalue of type
809 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +0000810 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
811 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000812 if (FromBuiltin->getKind() == BuiltinType::Float &&
813 ToBuiltin->getKind() == BuiltinType::Double)
814 return true;
815
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000816 // C99 6.3.1.5p1:
817 // When a float is promoted to double or long double, or a
818 // double is promoted to long double [...].
819 if (!getLangOptions().CPlusPlus &&
820 (FromBuiltin->getKind() == BuiltinType::Float ||
821 FromBuiltin->getKind() == BuiltinType::Double) &&
822 (ToBuiltin->getKind() == BuiltinType::LongDouble))
823 return true;
824 }
825
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000826 return false;
827}
828
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000829/// \brief Determine if a conversion is a complex promotion.
830///
831/// A complex promotion is defined as a complex -> complex conversion
832/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000833/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000834bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000835 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000836 if (!FromComplex)
837 return false;
838
John McCall183700f2009-09-21 23:43:11 +0000839 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000840 if (!ToComplex)
841 return false;
842
843 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000844 ToComplex->getElementType()) ||
845 IsIntegralPromotion(0, FromComplex->getElementType(),
846 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000847}
848
Douglas Gregorcb7de522008-11-26 23:31:11 +0000849/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
850/// the pointer type FromPtr to a pointer to type ToPointee, with the
851/// same type qualifiers as FromPtr has on its pointee type. ToType,
852/// if non-empty, will be a pointer to ToType that may or may not have
853/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +0000854static QualType
855BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000856 QualType ToPointee, QualType ToType,
857 ASTContext &Context) {
858 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
859 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +0000860 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +0000861
862 // Exact qualifier match -> return the pointer type we're converting to.
John McCall0953e762009-09-24 19:53:00 +0000863 if (CanonToPointee.getQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +0000864 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +0000865 if (!ToType.isNull())
Douglas Gregorcb7de522008-11-26 23:31:11 +0000866 return ToType;
867
868 // Build a pointer to ToPointee. It has the right qualifiers
869 // already.
870 return Context.getPointerType(ToPointee);
871 }
872
873 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +0000874 return Context.getPointerType(
875 Context.getQualifiedType(CanonToPointee.getUnqualifiedType(), Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +0000876}
877
Mike Stump1eb44332009-09-09 15:08:12 +0000878static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000879 bool InOverloadResolution,
880 ASTContext &Context) {
881 // Handle value-dependent integral null pointer constants correctly.
882 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
883 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
884 Expr->getType()->isIntegralType())
885 return !InOverloadResolution;
886
Douglas Gregorce940492009-09-25 04:25:58 +0000887 return Expr->isNullPointerConstant(Context,
888 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
889 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000890}
Mike Stump1eb44332009-09-09 15:08:12 +0000891
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000892/// IsPointerConversion - Determines whether the conversion of the
893/// expression From, which has the (possibly adjusted) type FromType,
894/// can be converted to the type ToType via a pointer conversion (C++
895/// 4.10). If so, returns true and places the converted type (that
896/// might differ from ToType in its cv-qualifiers at some level) into
897/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000898///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000899/// This routine also supports conversions to and from block pointers
900/// and conversions with Objective-C's 'id', 'id<protocols...>', and
901/// pointers to interfaces. FIXME: Once we've determined the
902/// appropriate overloading rules for Objective-C, we may want to
903/// split the Objective-C checks into a different routine; however,
904/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000905/// conversions, so for now they live here. IncompatibleObjC will be
906/// set if the conversion is an allowed Objective-C conversion that
907/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000908bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000909 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +0000910 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +0000911 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +0000912 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000913 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
914 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000915
Mike Stump1eb44332009-09-09 15:08:12 +0000916 // Conversion from a null pointer constant to any Objective-C pointer type.
917 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000918 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +0000919 ConvertedType = ToType;
920 return true;
921 }
922
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000923 // Blocks: Block pointers can be converted to void*.
924 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000925 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000926 ConvertedType = ToType;
927 return true;
928 }
929 // Blocks: A null pointer constant can be converted to a block
930 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +0000931 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000932 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000933 ConvertedType = ToType;
934 return true;
935 }
936
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000937 // If the left-hand-side is nullptr_t, the right side can be a null
938 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +0000939 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000940 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000941 ConvertedType = ToType;
942 return true;
943 }
944
Ted Kremenek6217b802009-07-29 21:53:49 +0000945 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000946 if (!ToTypePtr)
947 return false;
948
949 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000950 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000951 ConvertedType = ToType;
952 return true;
953 }
Sebastian Redl07779722008-10-31 14:43:28 +0000954
Douglas Gregorcb7de522008-11-26 23:31:11 +0000955 // Beyond this point, both types need to be pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +0000956 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +0000957 if (!FromTypePtr)
958 return false;
959
960 QualType FromPointeeType = FromTypePtr->getPointeeType();
961 QualType ToPointeeType = ToTypePtr->getPointeeType();
962
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000963 // An rvalue of type "pointer to cv T," where T is an object type,
964 // can be converted to an rvalue of type "pointer to cv void" (C++
965 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +0000966 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000967 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +0000968 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000969 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000970 return true;
971 }
972
Douglas Gregorf9201e02009-02-11 23:02:49 +0000973 // When we're overloading in C, we allow a special kind of pointer
974 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +0000975 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +0000976 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000977 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000978 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +0000979 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +0000980 return true;
981 }
982
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000983 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +0000984 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000985 // An rvalue of type "pointer to cv D," where D is a class type,
986 // can be converted to an rvalue of type "pointer to cv B," where
987 // B is a base class (clause 10) of D. If B is an inaccessible
988 // (clause 11) or ambiguous (10.2) base class of D, a program that
989 // necessitates this conversion is ill-formed. The result of the
990 // conversion is a pointer to the base class sub-object of the
991 // derived class object. The null pointer value is converted to
992 // the null pointer value of the destination type.
993 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000994 // Note that we do not check for ambiguity or inaccessibility
995 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +0000996 if (getLangOptions().CPlusPlus &&
997 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorcb7de522008-11-26 23:31:11 +0000998 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000999 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001000 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001001 ToType, Context);
1002 return true;
1003 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001004
Douglas Gregorc7887512008-12-19 19:13:09 +00001005 return false;
1006}
1007
1008/// isObjCPointerConversion - Determines whether this is an
1009/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1010/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001011bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001012 QualType& ConvertedType,
1013 bool &IncompatibleObjC) {
1014 if (!getLangOptions().ObjC1)
1015 return false;
1016
Steve Naroff14108da2009-07-10 23:34:53 +00001017 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001018 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001019 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001020 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001021
Steve Naroff14108da2009-07-10 23:34:53 +00001022 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001023 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001024 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001025 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001026 ConvertedType = ToType;
1027 return true;
1028 }
1029 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001030 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001031 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001032 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001033 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001034 ConvertedType = ToType;
1035 return true;
1036 }
1037 // Objective C++: We're able to convert from a pointer to an
1038 // interface to a pointer to a different interface.
1039 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1040 ConvertedType = ToType;
1041 return true;
1042 }
1043
1044 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1045 // Okay: this is some kind of implicit downcast of Objective-C
1046 // interfaces, which is permitted. However, we're going to
1047 // complain about it.
1048 IncompatibleObjC = true;
1049 ConvertedType = FromType;
1050 return true;
1051 }
Mike Stump1eb44332009-09-09 15:08:12 +00001052 }
Steve Naroff14108da2009-07-10 23:34:53 +00001053 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001054 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001055 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001056 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001057 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001058 ToPointeeType = ToBlockPtr->getPointeeType();
1059 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001060 return false;
1061
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001062 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001063 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001064 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001065 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001066 FromPointeeType = FromBlockPtr->getPointeeType();
1067 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001068 return false;
1069
Douglas Gregorc7887512008-12-19 19:13:09 +00001070 // If we have pointers to pointers, recursively check whether this
1071 // is an Objective-C conversion.
1072 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1073 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1074 IncompatibleObjC)) {
1075 // We always complain about this conversion.
1076 IncompatibleObjC = true;
1077 ConvertedType = ToType;
1078 return true;
1079 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001080 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001081 // differences in the argument and result types are in Objective-C
1082 // pointer conversions. If so, we permit the conversion (but
1083 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001084 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001085 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001086 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001087 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001088 if (FromFunctionType && ToFunctionType) {
1089 // If the function types are exactly the same, this isn't an
1090 // Objective-C pointer conversion.
1091 if (Context.getCanonicalType(FromPointeeType)
1092 == Context.getCanonicalType(ToPointeeType))
1093 return false;
1094
1095 // Perform the quick checks that will tell us whether these
1096 // function types are obviously different.
1097 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1098 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1099 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1100 return false;
1101
1102 bool HasObjCConversion = false;
1103 if (Context.getCanonicalType(FromFunctionType->getResultType())
1104 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1105 // Okay, the types match exactly. Nothing to do.
1106 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1107 ToFunctionType->getResultType(),
1108 ConvertedType, IncompatibleObjC)) {
1109 // Okay, we have an Objective-C pointer conversion.
1110 HasObjCConversion = true;
1111 } else {
1112 // Function types are too different. Abort.
1113 return false;
1114 }
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Douglas Gregorc7887512008-12-19 19:13:09 +00001116 // Check argument types.
1117 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1118 ArgIdx != NumArgs; ++ArgIdx) {
1119 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1120 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1121 if (Context.getCanonicalType(FromArgType)
1122 == Context.getCanonicalType(ToArgType)) {
1123 // Okay, the types match exactly. Nothing to do.
1124 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1125 ConvertedType, IncompatibleObjC)) {
1126 // Okay, we have an Objective-C pointer conversion.
1127 HasObjCConversion = true;
1128 } else {
1129 // Argument types are too different. Abort.
1130 return false;
1131 }
1132 }
1133
1134 if (HasObjCConversion) {
1135 // We had an Objective-C conversion. Allow this pointer
1136 // conversion, but complain about it.
1137 ConvertedType = ToType;
1138 IncompatibleObjC = true;
1139 return true;
1140 }
1141 }
1142
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001143 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001144}
1145
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001146/// CheckPointerConversion - Check the pointer conversion from the
1147/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001148/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001149/// conversions for which IsPointerConversion has already returned
1150/// true. It returns true and produces a diagnostic if there was an
1151/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001152bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
1153 CastExpr::CastKind &Kind) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001154 QualType FromType = From->getType();
1155
Ted Kremenek6217b802009-07-29 21:53:49 +00001156 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1157 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001158 QualType FromPointeeType = FromPtrType->getPointeeType(),
1159 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001160
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001161 if (FromPointeeType->isRecordType() &&
1162 ToPointeeType->isRecordType()) {
1163 // We must have a derived-to-base conversion. Check an
1164 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001165 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1166 From->getExprLoc(),
1167 From->getSourceRange()))
1168 return true;
1169
1170 // The conversion was successful.
1171 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001172 }
1173 }
Mike Stump1eb44332009-09-09 15:08:12 +00001174 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001175 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001176 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001177 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001178 // Objective-C++ conversions are always okay.
1179 // FIXME: We should have a different class of conversions for the
1180 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001181 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001182 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001183
Steve Naroff14108da2009-07-10 23:34:53 +00001184 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001185 return false;
1186}
1187
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001188/// IsMemberPointerConversion - Determines whether the conversion of the
1189/// expression From, which has the (possibly adjusted) type FromType, can be
1190/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1191/// If so, returns true and places the converted type (that might differ from
1192/// ToType in its cv-qualifiers at some level) into ConvertedType.
1193bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001194 QualType ToType,
1195 bool InOverloadResolution,
1196 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001197 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001198 if (!ToTypePtr)
1199 return false;
1200
1201 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001202 if (From->isNullPointerConstant(Context,
1203 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1204 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001205 ConvertedType = ToType;
1206 return true;
1207 }
1208
1209 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001210 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001211 if (!FromTypePtr)
1212 return false;
1213
1214 // A pointer to member of B can be converted to a pointer to member of D,
1215 // where D is derived from B (C++ 4.11p2).
1216 QualType FromClass(FromTypePtr->getClass(), 0);
1217 QualType ToClass(ToTypePtr->getClass(), 0);
1218 // FIXME: What happens when these are dependent? Is this function even called?
1219
1220 if (IsDerivedFrom(ToClass, FromClass)) {
1221 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1222 ToClass.getTypePtr());
1223 return true;
1224 }
1225
1226 return false;
1227}
1228
1229/// CheckMemberPointerConversion - Check the member pointer conversion from the
1230/// expression From to the type ToType. This routine checks for ambiguous or
1231/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1232/// for which IsMemberPointerConversion has already returned true. It returns
1233/// true and produces a diagnostic if there was an error, or returns false
1234/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001235bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001236 CastExpr::CastKind &Kind) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001237 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001238 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001239 if (!FromPtrType) {
1240 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001241 assert(From->isNullPointerConstant(Context,
1242 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001243 "Expr must be null pointer constant!");
1244 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001245 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001246 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001247
Ted Kremenek6217b802009-07-29 21:53:49 +00001248 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001249 assert(ToPtrType && "No member pointer cast has a target type "
1250 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001251
Sebastian Redl21593ac2009-01-28 18:33:18 +00001252 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1253 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001254
Sebastian Redl21593ac2009-01-28 18:33:18 +00001255 // FIXME: What about dependent types?
1256 assert(FromClass->isRecordType() && "Pointer into non-class.");
1257 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001258
Sebastian Redl21593ac2009-01-28 18:33:18 +00001259 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1260 /*DetectVirtual=*/true);
1261 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1262 assert(DerivationOkay &&
1263 "Should not have been called if derivation isn't OK.");
1264 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001265
Sebastian Redl21593ac2009-01-28 18:33:18 +00001266 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1267 getUnqualifiedType())) {
1268 // Derivation is ambiguous. Redo the check to find the exact paths.
1269 Paths.clear();
1270 Paths.setRecordingPaths(true);
1271 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1272 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1273 (void)StillOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001274
Sebastian Redl21593ac2009-01-28 18:33:18 +00001275 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1276 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1277 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1278 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001279 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001280
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001281 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001282 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1283 << FromClass << ToClass << QualType(VBase, 0)
1284 << From->getSourceRange();
1285 return true;
1286 }
1287
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001288 // Must be a base to derived member conversion.
1289 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001290 return false;
1291}
1292
Douglas Gregor98cd5992008-10-21 23:43:52 +00001293/// IsQualificationConversion - Determines whether the conversion from
1294/// an rvalue of type FromType to ToType is a qualification conversion
1295/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001296bool
1297Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001298 FromType = Context.getCanonicalType(FromType);
1299 ToType = Context.getCanonicalType(ToType);
1300
1301 // If FromType and ToType are the same type, this is not a
1302 // qualification conversion.
1303 if (FromType == ToType)
1304 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001305
Douglas Gregor98cd5992008-10-21 23:43:52 +00001306 // (C++ 4.4p4):
1307 // A conversion can add cv-qualifiers at levels other than the first
1308 // in multi-level pointers, subject to the following rules: [...]
1309 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001310 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001311 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001312 // Within each iteration of the loop, we check the qualifiers to
1313 // determine if this still looks like a qualification
1314 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001315 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001316 // until there are no more pointers or pointers-to-members left to
1317 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001318 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001319
1320 // -- for every j > 0, if const is in cv 1,j then const is in cv
1321 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001322 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001323 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001324
Douglas Gregor98cd5992008-10-21 23:43:52 +00001325 // -- if the cv 1,j and cv 2,j are different, then const is in
1326 // every cv for 0 < k < j.
1327 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001328 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001329 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001330
Douglas Gregor98cd5992008-10-21 23:43:52 +00001331 // Keep track of whether all prior cv-qualifiers in the "to" type
1332 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001333 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001334 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001335 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001336
1337 // We are left with FromType and ToType being the pointee types
1338 // after unwrapping the original FromType and ToType the same number
1339 // of types. If we unwrapped any pointers, and if FromType and
1340 // ToType have the same unqualified type (since we checked
1341 // qualifiers above), then this is a qualification conversion.
1342 return UnwrappedAnyPointer &&
1343 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1344}
1345
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001346/// \brief Given a function template or function, extract the function template
1347/// declaration (if any) and the underlying function declaration.
1348template<typename T>
1349static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1350 FunctionTemplateDecl *&FunctionTemplate) {
1351 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1352 if (FunctionTemplate)
1353 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1354 else
1355 Function = cast<T>(Orig);
1356}
1357
Douglas Gregor734d9862009-01-30 23:27:23 +00001358/// Determines whether there is a user-defined conversion sequence
1359/// (C++ [over.ics.user]) that converts expression From to the type
1360/// ToType. If such a conversion exists, User will contain the
1361/// user-defined conversion sequence that performs such a conversion
1362/// and this routine will return true. Otherwise, this routine returns
1363/// false and User is unspecified.
1364///
1365/// \param AllowConversionFunctions true if the conversion should
1366/// consider conversion functions at all. If false, only constructors
1367/// will be considered.
1368///
1369/// \param AllowExplicit true if the conversion should consider C++0x
1370/// "explicit" conversion functions as well as non-explicit conversion
1371/// functions (C++0x [class.conv.fct]p2).
Sebastian Redle2b68332009-04-12 17:16:29 +00001372///
1373/// \param ForceRValue true if the expression should be treated as an rvalue
1374/// for overload resolution.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001375Sema::OverloadingResult Sema::IsUserDefinedConversion(
1376 Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001377 UserDefinedConversionSequence& User,
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +00001378 OverloadCandidateSet& CandidateSet,
Douglas Gregor734d9862009-01-30 23:27:23 +00001379 bool AllowConversionFunctions,
Mike Stump1eb44332009-09-09 15:08:12 +00001380 bool AllowExplicit, bool ForceRValue) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001381 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001382 if (CXXRecordDecl *ToRecordDecl
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001383 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1384 // C++ [over.match.ctor]p1:
1385 // When objects of class type are direct-initialized (8.5), or
1386 // copy-initialized from an expression of the same or a
1387 // derived class type (8.5), overload resolution selects the
1388 // constructor. [...] For copy-initialization, the candidate
1389 // functions are all the converting constructors (12.3.1) of
1390 // that class. The argument list is the expression-list within
1391 // the parentheses of the initializer.
Mike Stump1eb44332009-09-09 15:08:12 +00001392 DeclarationName ConstructorName
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001393 = Context.DeclarationNames.getCXXConstructorName(
1394 Context.getCanonicalType(ToType).getUnqualifiedType());
1395 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump1eb44332009-09-09 15:08:12 +00001396 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001397 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001398 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00001399 // Find the constructor (which may be a template).
1400 CXXConstructorDecl *Constructor = 0;
1401 FunctionTemplateDecl *ConstructorTmpl
1402 = dyn_cast<FunctionTemplateDecl>(*Con);
1403 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001404 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001405 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1406 else
1407 Constructor = cast<CXXConstructorDecl>(*Con);
Mike Stump1eb44332009-09-09 15:08:12 +00001408
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001409 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001410 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001411 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001412 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
Douglas Gregordec06662009-08-21 18:42:58 +00001413 1, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00001414 /*SuppressUserConversions=*/true,
Douglas Gregordec06662009-08-21 18:42:58 +00001415 ForceRValue);
1416 else
1417 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1418 /*SuppressUserConversions=*/true, ForceRValue);
1419 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001420 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001421 }
1422 }
1423
Douglas Gregor734d9862009-01-30 23:27:23 +00001424 if (!AllowConversionFunctions) {
1425 // Don't allow any conversion functions to enter the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00001426 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1427 PDiag(0)
Anders Carlssonb7906612009-08-26 23:45:07 +00001428 << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001429 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001430 } else if (const RecordType *FromRecordType
Ted Kremenek6217b802009-07-29 21:53:49 +00001431 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001432 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001433 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1434 // Add all of the conversion functions as candidates.
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001435 OverloadedFunctionDecl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001436 = FromRecordDecl->getVisibleConversionFunctions();
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001437 for (OverloadedFunctionDecl::function_iterator Func
1438 = Conversions->function_begin();
1439 Func != Conversions->function_end(); ++Func) {
1440 CXXConversionDecl *Conv;
1441 FunctionTemplateDecl *ConvTemplate;
1442 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1443 if (ConvTemplate)
1444 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1445 else
1446 Conv = dyn_cast<CXXConversionDecl>(*Func);
1447
1448 if (AllowExplicit || !Conv->isExplicit()) {
1449 if (ConvTemplate)
1450 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1451 CandidateSet);
1452 else
1453 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1454 }
1455 }
1456 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001457 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001458
1459 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001460 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001461 case OR_Success:
1462 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001463 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001464 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1465 // C++ [over.ics.user]p1:
1466 // If the user-defined conversion is specified by a
1467 // constructor (12.3.1), the initial standard conversion
1468 // sequence converts the source type to the type required by
1469 // the argument of the constructor.
1470 //
1471 // FIXME: What about ellipsis conversions?
1472 QualType ThisType = Constructor->getThisType(Context);
1473 User.Before = Best->Conversions[0].Standard;
1474 User.ConversionFunction = Constructor;
1475 User.After.setAsIdentityConversion();
Mike Stump1eb44332009-09-09 15:08:12 +00001476 User.After.FromTypePtr
Ted Kremenek6217b802009-07-29 21:53:49 +00001477 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor60d62c22008-10-31 16:23:19 +00001478 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001479 return OR_Success;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001480 } else if (CXXConversionDecl *Conversion
1481 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1482 // C++ [over.ics.user]p1:
1483 //
1484 // [...] If the user-defined conversion is specified by a
1485 // conversion function (12.3.2), the initial standard
1486 // conversion sequence converts the source type to the
1487 // implicit object parameter of the conversion function.
1488 User.Before = Best->Conversions[0].Standard;
1489 User.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00001490
1491 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001492 // The second standard conversion sequence converts the
1493 // result of the user-defined conversion to the target type
1494 // for the sequence. Since an implicit conversion sequence
1495 // is an initialization, the special rules for
1496 // initialization by user-defined conversion apply when
1497 // selecting the best user-defined conversion for a
1498 // user-defined conversion sequence (see 13.3.3 and
1499 // 13.3.3.1).
1500 User.After = Best->FinalConversion;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001501 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001502 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001503 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001504 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001505 }
Mike Stump1eb44332009-09-09 15:08:12 +00001506
Douglas Gregor60d62c22008-10-31 16:23:19 +00001507 case OR_No_Viable_Function:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001508 return OR_No_Viable_Function;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001509 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001510 // No conversion here! We're done.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001511 return OR_Deleted;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001512
1513 case OR_Ambiguous:
1514 // FIXME: See C++ [over.best.ics]p10 for the handling of
1515 // ambiguous conversion sequences.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001516 return OR_Ambiguous;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001517 }
1518
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001519 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001520}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001521
1522bool
1523Sema::DiagnoseAmbiguousUserDefinedConversion(Expr *From, QualType ToType) {
1524 ImplicitConversionSequence ICS;
1525 OverloadCandidateSet CandidateSet;
1526 OverloadingResult OvResult =
1527 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1528 CandidateSet, true, false, false);
1529 if (OvResult != OR_Ambiguous)
1530 return false;
1531 Diag(From->getSourceRange().getBegin(),
1532 diag::err_typecheck_ambiguous_condition)
1533 << From->getType() << ToType << From->getSourceRange();
1534 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1535 return true;
1536}
Douglas Gregor60d62c22008-10-31 16:23:19 +00001537
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001538/// CompareImplicitConversionSequences - Compare two implicit
1539/// conversion sequences to determine whether one is better than the
1540/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00001541ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001542Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1543 const ImplicitConversionSequence& ICS2)
1544{
1545 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1546 // conversion sequences (as defined in 13.3.3.1)
1547 // -- a standard conversion sequence (13.3.3.1.1) is a better
1548 // conversion sequence than a user-defined conversion sequence or
1549 // an ellipsis conversion sequence, and
1550 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1551 // conversion sequence than an ellipsis conversion sequence
1552 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00001553 //
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001554 if (ICS1.ConversionKind < ICS2.ConversionKind)
1555 return ImplicitConversionSequence::Better;
1556 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1557 return ImplicitConversionSequence::Worse;
1558
1559 // Two implicit conversion sequences of the same form are
1560 // indistinguishable conversion sequences unless one of the
1561 // following rules apply: (C++ 13.3.3.2p3):
1562 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1563 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump1eb44332009-09-09 15:08:12 +00001564 else if (ICS1.ConversionKind ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001565 ImplicitConversionSequence::UserDefinedConversion) {
1566 // User-defined conversion sequence U1 is a better conversion
1567 // sequence than another user-defined conversion sequence U2 if
1568 // they contain the same user-defined conversion function or
1569 // constructor and if the second standard conversion sequence of
1570 // U1 is better than the second standard conversion sequence of
1571 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001572 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001573 ICS2.UserDefined.ConversionFunction)
1574 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1575 ICS2.UserDefined.After);
1576 }
1577
1578 return ImplicitConversionSequence::Indistinguishable;
1579}
1580
1581/// CompareStandardConversionSequences - Compare two standard
1582/// conversion sequences to determine whether one is better than the
1583/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001584ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001585Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1586 const StandardConversionSequence& SCS2)
1587{
1588 // Standard conversion sequence S1 is a better conversion sequence
1589 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1590
1591 // -- S1 is a proper subsequence of S2 (comparing the conversion
1592 // sequences in the canonical form defined by 13.3.3.1.1,
1593 // excluding any Lvalue Transformation; the identity conversion
1594 // sequence is considered to be a subsequence of any
1595 // non-identity conversion sequence) or, if not that,
1596 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1597 // Neither is a proper subsequence of the other. Do nothing.
1598 ;
1599 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1600 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001601 (SCS1.Second == ICK_Identity &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001602 SCS1.Third == ICK_Identity))
1603 // SCS1 is a proper subsequence of SCS2.
1604 return ImplicitConversionSequence::Better;
1605 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1606 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001607 (SCS2.Second == ICK_Identity &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001608 SCS2.Third == ICK_Identity))
1609 // SCS2 is a proper subsequence of SCS1.
1610 return ImplicitConversionSequence::Worse;
1611
1612 // -- the rank of S1 is better than the rank of S2 (by the rules
1613 // defined below), or, if not that,
1614 ImplicitConversionRank Rank1 = SCS1.getRank();
1615 ImplicitConversionRank Rank2 = SCS2.getRank();
1616 if (Rank1 < Rank2)
1617 return ImplicitConversionSequence::Better;
1618 else if (Rank2 < Rank1)
1619 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001620
Douglas Gregor57373262008-10-22 14:17:15 +00001621 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1622 // are indistinguishable unless one of the following rules
1623 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Douglas Gregor57373262008-10-22 14:17:15 +00001625 // A conversion that is not a conversion of a pointer, or
1626 // pointer to member, to bool is better than another conversion
1627 // that is such a conversion.
1628 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1629 return SCS2.isPointerConversionToBool()
1630 ? ImplicitConversionSequence::Better
1631 : ImplicitConversionSequence::Worse;
1632
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001633 // C++ [over.ics.rank]p4b2:
1634 //
1635 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001636 // conversion of B* to A* is better than conversion of B* to
1637 // void*, and conversion of A* to void* is better than conversion
1638 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00001639 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001640 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001641 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001642 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001643 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1644 // Exactly one of the conversion sequences is a conversion to
1645 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001646 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1647 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001648 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1649 // Neither conversion sequence converts to a void pointer; compare
1650 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001651 if (ImplicitConversionSequence::CompareKind DerivedCK
1652 = CompareDerivedToBaseConversions(SCS1, SCS2))
1653 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001654 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1655 // Both conversion sequences are conversions to void
1656 // pointers. Compare the source types to determine if there's an
1657 // inheritance relationship in their sources.
1658 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1659 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1660
1661 // Adjust the types we're converting from via the array-to-pointer
1662 // conversion, if we need to.
1663 if (SCS1.First == ICK_Array_To_Pointer)
1664 FromType1 = Context.getArrayDecayedType(FromType1);
1665 if (SCS2.First == ICK_Array_To_Pointer)
1666 FromType2 = Context.getArrayDecayedType(FromType2);
1667
Mike Stump1eb44332009-09-09 15:08:12 +00001668 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001669 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001670 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001671 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001672
1673 if (IsDerivedFrom(FromPointee2, FromPointee1))
1674 return ImplicitConversionSequence::Better;
1675 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1676 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001677
1678 // Objective-C++: If one interface is more specific than the
1679 // other, it is the better one.
John McCall183700f2009-09-21 23:43:11 +00001680 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1681 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001682 if (FromIface1 && FromIface1) {
1683 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1684 return ImplicitConversionSequence::Better;
1685 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1686 return ImplicitConversionSequence::Worse;
1687 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001688 }
Douglas Gregor57373262008-10-22 14:17:15 +00001689
1690 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1691 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00001692 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001693 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001694 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001695
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001696 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001697 // C++0x [over.ics.rank]p3b4:
1698 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1699 // implicit object parameter of a non-static member function declared
1700 // without a ref-qualifier, and S1 binds an rvalue reference to an
1701 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00001702 // FIXME: We don't know if we're dealing with the implicit object parameter,
1703 // or if the member function in this case has a ref qualifier.
1704 // (Of course, we don't have ref qualifiers yet.)
1705 if (SCS1.RRefBinding != SCS2.RRefBinding)
1706 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1707 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001708
1709 // C++ [over.ics.rank]p3b4:
1710 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1711 // which the references refer are the same type except for
1712 // top-level cv-qualifiers, and the type to which the reference
1713 // initialized by S2 refers is more cv-qualified than the type
1714 // to which the reference initialized by S1 refers.
Sebastian Redla9845802009-03-29 15:27:50 +00001715 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1716 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001717 T1 = Context.getCanonicalType(T1);
1718 T2 = Context.getCanonicalType(T2);
1719 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1720 if (T2.isMoreQualifiedThan(T1))
1721 return ImplicitConversionSequence::Better;
1722 else if (T1.isMoreQualifiedThan(T2))
1723 return ImplicitConversionSequence::Worse;
1724 }
1725 }
Douglas Gregor57373262008-10-22 14:17:15 +00001726
1727 return ImplicitConversionSequence::Indistinguishable;
1728}
1729
1730/// CompareQualificationConversions - Compares two standard conversion
1731/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00001732/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1733ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00001734Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00001735 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00001736 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001737 // -- S1 and S2 differ only in their qualification conversion and
1738 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1739 // cv-qualification signature of type T1 is a proper subset of
1740 // the cv-qualification signature of type T2, and S1 is not the
1741 // deprecated string literal array-to-pointer conversion (4.2).
1742 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1743 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1744 return ImplicitConversionSequence::Indistinguishable;
1745
1746 // FIXME: the example in the standard doesn't use a qualification
1747 // conversion (!)
1748 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1749 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1750 T1 = Context.getCanonicalType(T1);
1751 T2 = Context.getCanonicalType(T2);
1752
1753 // If the types are the same, we won't learn anything by unwrapped
1754 // them.
1755 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1756 return ImplicitConversionSequence::Indistinguishable;
1757
Mike Stump1eb44332009-09-09 15:08:12 +00001758 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00001759 = ImplicitConversionSequence::Indistinguishable;
1760 while (UnwrapSimilarPointerTypes(T1, T2)) {
1761 // Within each iteration of the loop, we check the qualifiers to
1762 // determine if this still looks like a qualification
1763 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001764 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001765 // until there are no more pointers or pointers-to-members left
1766 // to unwrap. This essentially mimics what
1767 // IsQualificationConversion does, but here we're checking for a
1768 // strict subset of qualifiers.
1769 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1770 // The qualifiers are the same, so this doesn't tell us anything
1771 // about how the sequences rank.
1772 ;
1773 else if (T2.isMoreQualifiedThan(T1)) {
1774 // T1 has fewer qualifiers, so it could be the better sequence.
1775 if (Result == ImplicitConversionSequence::Worse)
1776 // Neither has qualifiers that are a subset of the other's
1777 // qualifiers.
1778 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001779
Douglas Gregor57373262008-10-22 14:17:15 +00001780 Result = ImplicitConversionSequence::Better;
1781 } else if (T1.isMoreQualifiedThan(T2)) {
1782 // T2 has fewer qualifiers, so it could be the better sequence.
1783 if (Result == ImplicitConversionSequence::Better)
1784 // Neither has qualifiers that are a subset of the other's
1785 // qualifiers.
1786 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Douglas Gregor57373262008-10-22 14:17:15 +00001788 Result = ImplicitConversionSequence::Worse;
1789 } else {
1790 // Qualifiers are disjoint.
1791 return ImplicitConversionSequence::Indistinguishable;
1792 }
1793
1794 // If the types after this point are equivalent, we're done.
1795 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1796 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001797 }
1798
Douglas Gregor57373262008-10-22 14:17:15 +00001799 // Check that the winning standard conversion sequence isn't using
1800 // the deprecated string literal array to pointer conversion.
1801 switch (Result) {
1802 case ImplicitConversionSequence::Better:
1803 if (SCS1.Deprecated)
1804 Result = ImplicitConversionSequence::Indistinguishable;
1805 break;
1806
1807 case ImplicitConversionSequence::Indistinguishable:
1808 break;
1809
1810 case ImplicitConversionSequence::Worse:
1811 if (SCS2.Deprecated)
1812 Result = ImplicitConversionSequence::Indistinguishable;
1813 break;
1814 }
1815
1816 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001817}
1818
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001819/// CompareDerivedToBaseConversions - Compares two standard conversion
1820/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001821/// various kinds of derived-to-base conversions (C++
1822/// [over.ics.rank]p4b3). As part of these checks, we also look at
1823/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001824ImplicitConversionSequence::CompareKind
1825Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1826 const StandardConversionSequence& SCS2) {
1827 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1828 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1829 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1830 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1831
1832 // Adjust the types we're converting from via the array-to-pointer
1833 // conversion, if we need to.
1834 if (SCS1.First == ICK_Array_To_Pointer)
1835 FromType1 = Context.getArrayDecayedType(FromType1);
1836 if (SCS2.First == ICK_Array_To_Pointer)
1837 FromType2 = Context.getArrayDecayedType(FromType2);
1838
1839 // Canonicalize all of the types.
1840 FromType1 = Context.getCanonicalType(FromType1);
1841 ToType1 = Context.getCanonicalType(ToType1);
1842 FromType2 = Context.getCanonicalType(FromType2);
1843 ToType2 = Context.getCanonicalType(ToType2);
1844
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001845 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001846 //
1847 // If class B is derived directly or indirectly from class A and
1848 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001849 //
1850 // For Objective-C, we let A, B, and C also be Objective-C
1851 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001852
1853 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00001854 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001855 SCS2.Second == ICK_Pointer_Conversion &&
1856 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1857 FromType1->isPointerType() && FromType2->isPointerType() &&
1858 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001859 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001860 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00001861 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001862 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001863 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001864 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001865 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001866 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001867
John McCall183700f2009-09-21 23:43:11 +00001868 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1869 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1870 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1871 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001872
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001873 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001874 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1875 if (IsDerivedFrom(ToPointee1, ToPointee2))
1876 return ImplicitConversionSequence::Better;
1877 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1878 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001879
1880 if (ToIface1 && ToIface2) {
1881 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1882 return ImplicitConversionSequence::Better;
1883 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1884 return ImplicitConversionSequence::Worse;
1885 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001886 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001887
1888 // -- conversion of B* to A* is better than conversion of C* to A*,
1889 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1890 if (IsDerivedFrom(FromPointee2, FromPointee1))
1891 return ImplicitConversionSequence::Better;
1892 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1893 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00001894
Douglas Gregorcb7de522008-11-26 23:31:11 +00001895 if (FromIface1 && FromIface2) {
1896 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1897 return ImplicitConversionSequence::Better;
1898 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1899 return ImplicitConversionSequence::Worse;
1900 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001901 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001902 }
1903
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001904 // Compare based on reference bindings.
1905 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1906 SCS1.Second == ICK_Derived_To_Base) {
1907 // -- binding of an expression of type C to a reference of type
1908 // B& is better than binding an expression of type C to a
1909 // reference of type A&,
1910 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1911 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1912 if (IsDerivedFrom(ToType1, ToType2))
1913 return ImplicitConversionSequence::Better;
1914 else if (IsDerivedFrom(ToType2, ToType1))
1915 return ImplicitConversionSequence::Worse;
1916 }
1917
Douglas Gregor225c41e2008-11-03 19:09:14 +00001918 // -- binding of an expression of type B to a reference of type
1919 // A& is better than binding an expression of type C to a
1920 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001921 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1922 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1923 if (IsDerivedFrom(FromType2, FromType1))
1924 return ImplicitConversionSequence::Better;
1925 else if (IsDerivedFrom(FromType1, FromType2))
1926 return ImplicitConversionSequence::Worse;
1927 }
1928 }
1929
1930
1931 // FIXME: conversion of A::* to B::* is better than conversion of
1932 // A::* to C::*,
1933
1934 // FIXME: conversion of B::* to C::* is better than conversion of
1935 // A::* to C::*, and
1936
Douglas Gregor225c41e2008-11-03 19:09:14 +00001937 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1938 SCS1.Second == ICK_Derived_To_Base) {
1939 // -- conversion of C to B is better than conversion of C to A,
1940 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1941 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1942 if (IsDerivedFrom(ToType1, ToType2))
1943 return ImplicitConversionSequence::Better;
1944 else if (IsDerivedFrom(ToType2, ToType1))
1945 return ImplicitConversionSequence::Worse;
1946 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001947
Douglas Gregor225c41e2008-11-03 19:09:14 +00001948 // -- conversion of B to A is better than conversion of C to A.
1949 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1950 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1951 if (IsDerivedFrom(FromType2, FromType1))
1952 return ImplicitConversionSequence::Better;
1953 else if (IsDerivedFrom(FromType1, FromType2))
1954 return ImplicitConversionSequence::Worse;
1955 }
1956 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001957
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001958 return ImplicitConversionSequence::Indistinguishable;
1959}
1960
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001961/// TryCopyInitialization - Try to copy-initialize a value of type
1962/// ToType from the expression From. Return the implicit conversion
1963/// sequence required to pass this argument, which may be a bad
1964/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00001965/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redle2b68332009-04-12 17:16:29 +00001966/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1967/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00001968ImplicitConversionSequence
1969Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001970 bool SuppressUserConversions, bool ForceRValue,
1971 bool InOverloadResolution) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00001972 if (ToType->isReferenceType()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001973 ImplicitConversionSequence ICS;
Mike Stump1eb44332009-09-09 15:08:12 +00001974 CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00001975 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001976 SuppressUserConversions,
1977 /*AllowExplicit=*/false,
1978 ForceRValue,
1979 &ICS);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001980 return ICS;
1981 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001982 return TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001983 SuppressUserConversions,
1984 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001985 ForceRValue,
1986 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001987 }
1988}
1989
Sebastian Redle2b68332009-04-12 17:16:29 +00001990/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1991/// the expression @p From. Returns true (and emits a diagnostic) if there was
1992/// an error, returns false if the initialization succeeded. Elidable should
1993/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1994/// differently in C++0x for this case.
Mike Stump1eb44332009-09-09 15:08:12 +00001995bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +00001996 const char* Flavor, bool Elidable) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001997 if (!getLangOptions().CPlusPlus) {
1998 // In C, argument passing is the same as performing an assignment.
1999 QualType FromType = From->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002000
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002001 AssignConvertType ConvTy =
2002 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00002003 if (ConvTy != Compatible &&
2004 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2005 ConvTy = Compatible;
Mike Stump1eb44332009-09-09 15:08:12 +00002006
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002007 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2008 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002009 }
Sebastian Redle2b68332009-04-12 17:16:29 +00002010
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002011 if (ToType->isReferenceType())
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002012 return CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00002013 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002014 /*SuppressUserConversions=*/false,
2015 /*AllowExplicit=*/false,
2016 /*ForceRValue=*/false);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002017
Sebastian Redle2b68332009-04-12 17:16:29 +00002018 if (!PerformImplicitConversion(From, ToType, Flavor,
2019 /*AllowExplicit=*/false, Elidable))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002020 return false;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002021 if (!DiagnoseAmbiguousUserDefinedConversion(From, ToType))
Fariborz Jahanian455acd92009-09-22 19:53:15 +00002022 return Diag(From->getSourceRange().getBegin(),
2023 diag::err_typecheck_convert_incompatible)
2024 << ToType << From->getType() << Flavor << From->getSourceRange();
Fariborz Jahanian455acd92009-09-22 19:53:15 +00002025 return true;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002026}
2027
Douglas Gregor96176b32008-11-18 23:14:02 +00002028/// TryObjectArgumentInitialization - Try to initialize the object
2029/// parameter of the given member function (@c Method) from the
2030/// expression @p From.
2031ImplicitConversionSequence
2032Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
2033 QualType ClassType = Context.getTypeDeclType(Method->getParent());
John McCall0953e762009-09-24 19:53:00 +00002034 QualType ImplicitParamType
2035 = Context.getCVRQualifiedType(ClassType, Method->getTypeQualifiers());
Douglas Gregor96176b32008-11-18 23:14:02 +00002036
2037 // Set up the conversion sequence as a "bad" conversion, to allow us
2038 // to exit early.
2039 ImplicitConversionSequence ICS;
2040 ICS.Standard.setAsIdentityConversion();
2041 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2042
2043 // We need to have an object of class type.
2044 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002045 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00002046 FromType = PT->getPointeeType();
2047
2048 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002049
2050 // The implicit object parmeter is has the type "reference to cv X",
2051 // where X is the class of which the function is a member
2052 // (C++ [over.match.funcs]p4). However, when finding an implicit
2053 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00002054 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00002055 // (C++ [over.match.funcs]p5). We perform a simplified version of
2056 // reference binding here, that allows class rvalues to bind to
2057 // non-constant references.
2058
2059 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2060 // with the implicit object parameter (C++ [over.match.funcs]p5).
2061 QualType FromTypeCanon = Context.getCanonicalType(FromType);
2062 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2063 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2064 return ICS;
2065
2066 // Check that we have either the same type or a derived type. It
2067 // affects the conversion rank.
2068 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2069 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2070 ICS.Standard.Second = ICK_Identity;
2071 else if (IsDerivedFrom(FromType, ClassType))
2072 ICS.Standard.Second = ICK_Derived_To_Base;
2073 else
2074 return ICS;
2075
2076 // Success. Mark this as a reference binding.
2077 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2078 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2079 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2080 ICS.Standard.ReferenceBinding = true;
2081 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00002082 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002083 return ICS;
2084}
2085
2086/// PerformObjectArgumentInitialization - Perform initialization of
2087/// the implicit object parameter for the given Method with the given
2088/// expression.
2089bool
2090Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002091 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00002092 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00002093 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002094
Ted Kremenek6217b802009-07-29 21:53:49 +00002095 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002096 FromRecordType = PT->getPointeeType();
2097 DestType = Method->getThisType(Context);
2098 } else {
2099 FromRecordType = From->getType();
2100 DestType = ImplicitParamRecordType;
2101 }
2102
Mike Stump1eb44332009-09-09 15:08:12 +00002103 ImplicitConversionSequence ICS
Douglas Gregor96176b32008-11-18 23:14:02 +00002104 = TryObjectArgumentInitialization(From, Method);
2105 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2106 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002107 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00002108 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002109
Douglas Gregor96176b32008-11-18 23:14:02 +00002110 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssona552f7c2009-05-01 18:34:30 +00002111 CheckDerivedToBaseConversion(FromRecordType,
2112 ImplicitParamRecordType,
Douglas Gregor96176b32008-11-18 23:14:02 +00002113 From->getSourceRange().getBegin(),
2114 From->getSourceRange()))
2115 return true;
2116
Mike Stump1eb44332009-09-09 15:08:12 +00002117 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson116b7d92009-08-07 18:45:49 +00002118 /*isLvalue=*/true);
Douglas Gregor96176b32008-11-18 23:14:02 +00002119 return false;
2120}
2121
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002122/// TryContextuallyConvertToBool - Attempt to contextually convert the
2123/// expression From to bool (C++0x [conv]p3).
2124ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump1eb44332009-09-09 15:08:12 +00002125 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002126 // FIXME: Are these flags correct?
2127 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00002128 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00002129 /*ForceRValue=*/false,
2130 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002131}
2132
2133/// PerformContextuallyConvertToBool - Perform a contextual conversion
2134/// of the expression From to bool (C++0x [conv]p3).
2135bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2136 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2137 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2138 return false;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002139
2140 if (!DiagnoseAmbiguousUserDefinedConversion(From, Context.BoolTy))
2141 return Diag(From->getSourceRange().getBegin(),
2142 diag::err_typecheck_bool_condition)
2143 << From->getType() << From->getSourceRange();
2144 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002145}
2146
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002147/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00002148/// candidate functions, using the given function call arguments. If
2149/// @p SuppressUserConversions, then don't allow user-defined
2150/// conversions via constructors or conversion operators.
Sebastian Redle2b68332009-04-12 17:16:29 +00002151/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2152/// hacky way to implement the overloading rules for elidable copy
2153/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002154///
2155/// \para PartialOverloading true if we are performing "partial" overloading
2156/// based on an incomplete set of function arguments. This feature is used by
2157/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00002158void
2159Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002160 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002161 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00002162 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002163 bool ForceRValue,
2164 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00002165 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002166 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002167 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00002168 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002169 "Use AddConversionCandidate for conversion functions");
Mike Stump1eb44332009-09-09 15:08:12 +00002170 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00002171 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00002172
Douglas Gregor88a35142008-12-22 05:46:06 +00002173 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002174 if (!isa<CXXConstructorDecl>(Method)) {
2175 // If we get here, it's because we're calling a member function
2176 // that is named without a member access expression (e.g.,
2177 // "this->f") that was either written explicitly or created
2178 // implicitly. This can happen with a qualified call to a member
2179 // function, e.g., X::f(). We use a NULL object as the implied
2180 // object argument (C++ [over.call.func]p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002181 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002182 SuppressUserConversions, ForceRValue);
2183 return;
2184 }
2185 // We treat a constructor like a non-member function, since its object
2186 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00002187 }
2188
2189
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002190 // Add this candidate
2191 CandidateSet.push_back(OverloadCandidate());
2192 OverloadCandidate& Candidate = CandidateSet.back();
2193 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00002194 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002195 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002196 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002197
2198 unsigned NumArgsInProto = Proto->getNumArgs();
2199
2200 // (C++ 13.3.2p2): A candidate function having fewer than m
2201 // parameters is viable only if it has an ellipsis in its parameter
2202 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00002203 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2204 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002205 Candidate.Viable = false;
2206 return;
2207 }
2208
2209 // (C++ 13.3.2p2): A candidate function having more than m parameters
2210 // is viable only if the (m+1)st parameter has a default argument
2211 // (8.3.6). For the purposes of overload resolution, the
2212 // parameter list is truncated on the right, so that there are
2213 // exactly m parameters.
2214 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002215 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002216 // Not enough arguments.
2217 Candidate.Viable = false;
2218 return;
2219 }
2220
2221 // Determine the implicit conversion sequences for each of the
2222 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002223 Candidate.Conversions.resize(NumArgs);
2224 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2225 if (ArgIdx < NumArgsInProto) {
2226 // (C++ 13.3.2p3): for F to be a viable function, there shall
2227 // exist for each argument an implicit conversion sequence
2228 // (13.3.3.1) that converts that argument to the corresponding
2229 // parameter of F.
2230 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002231 Candidate.Conversions[ArgIdx]
2232 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002233 SuppressUserConversions, ForceRValue,
2234 /*InOverloadResolution=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00002235 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002236 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002237 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002238 break;
2239 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002240 } else {
2241 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2242 // argument for which there is no corresponding parameter is
2243 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002244 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002245 = ImplicitConversionSequence::EllipsisConversion;
2246 }
2247 }
2248}
2249
Douglas Gregor063daf62009-03-13 18:40:31 +00002250/// \brief Add all of the function declarations in the given function set to
2251/// the overload canddiate set.
2252void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2253 Expr **Args, unsigned NumArgs,
2254 OverloadCandidateSet& CandidateSet,
2255 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00002256 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor063daf62009-03-13 18:40:31 +00002257 FEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00002258 F != FEnd; ++F) {
2259 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
Mike Stump1eb44332009-09-09 15:08:12 +00002260 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00002261 SuppressUserConversions);
2262 else
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002263 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2264 /*FIXME: explicit args */false, 0, 0,
Mike Stump1eb44332009-09-09 15:08:12 +00002265 Args, NumArgs, CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00002266 SuppressUserConversions);
2267 }
Douglas Gregor063daf62009-03-13 18:40:31 +00002268}
2269
Douglas Gregor96176b32008-11-18 23:14:02 +00002270/// AddMethodCandidate - Adds the given C++ member function to the set
2271/// of candidate functions, using the given function call arguments
2272/// and the object argument (@c Object). For example, in a call
2273/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2274/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2275/// allow user-defined conversions via constructors or conversion
Sebastian Redle2b68332009-04-12 17:16:29 +00002276/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2277/// a slightly hacky way to implement the overloading rules for elidable copy
2278/// initialization in C++0x (C++0x 12.8p15).
Mike Stump1eb44332009-09-09 15:08:12 +00002279void
Douglas Gregor96176b32008-11-18 23:14:02 +00002280Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2281 Expr **Args, unsigned NumArgs,
2282 OverloadCandidateSet& CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00002283 bool SuppressUserConversions, bool ForceRValue) {
2284 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002285 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00002286 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002287 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor96176b32008-11-18 23:14:02 +00002288 "Use AddConversionCandidate for conversion functions");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002289 assert(!isa<CXXConstructorDecl>(Method) &&
2290 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00002291
2292 // Add this candidate
2293 CandidateSet.push_back(OverloadCandidate());
2294 OverloadCandidate& Candidate = CandidateSet.back();
2295 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002296 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002297 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002298
2299 unsigned NumArgsInProto = Proto->getNumArgs();
2300
2301 // (C++ 13.3.2p2): A candidate function having fewer than m
2302 // parameters is viable only if it has an ellipsis in its parameter
2303 // list (8.3.5).
2304 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2305 Candidate.Viable = false;
2306 return;
2307 }
2308
2309 // (C++ 13.3.2p2): A candidate function having more than m parameters
2310 // is viable only if the (m+1)st parameter has a default argument
2311 // (8.3.6). For the purposes of overload resolution, the
2312 // parameter list is truncated on the right, so that there are
2313 // exactly m parameters.
2314 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2315 if (NumArgs < MinRequiredArgs) {
2316 // Not enough arguments.
2317 Candidate.Viable = false;
2318 return;
2319 }
2320
2321 Candidate.Viable = true;
2322 Candidate.Conversions.resize(NumArgs + 1);
2323
Douglas Gregor88a35142008-12-22 05:46:06 +00002324 if (Method->isStatic() || !Object)
2325 // The implicit object argument is ignored.
2326 Candidate.IgnoreObjectArgument = true;
2327 else {
2328 // Determine the implicit conversion sequence for the object
2329 // parameter.
2330 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
Mike Stump1eb44332009-09-09 15:08:12 +00002331 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor88a35142008-12-22 05:46:06 +00002332 == ImplicitConversionSequence::BadConversion) {
2333 Candidate.Viable = false;
2334 return;
2335 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002336 }
2337
2338 // Determine the implicit conversion sequences for each of the
2339 // arguments.
2340 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2341 if (ArgIdx < NumArgsInProto) {
2342 // (C++ 13.3.2p3): for F to be a viable function, there shall
2343 // exist for each argument an implicit conversion sequence
2344 // (13.3.3.1) that converts that argument to the corresponding
2345 // parameter of F.
2346 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002347 Candidate.Conversions[ArgIdx + 1]
2348 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002349 SuppressUserConversions, ForceRValue,
Anders Carlsson08972922009-08-28 15:33:32 +00002350 /*InOverloadResolution=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00002351 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002352 == ImplicitConversionSequence::BadConversion) {
2353 Candidate.Viable = false;
2354 break;
2355 }
2356 } else {
2357 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2358 // argument for which there is no corresponding parameter is
2359 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002360 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002361 = ImplicitConversionSequence::EllipsisConversion;
2362 }
2363 }
2364}
2365
Douglas Gregor6b906862009-08-21 00:16:32 +00002366/// \brief Add a C++ member function template as a candidate to the candidate
2367/// set, using template argument deduction to produce an appropriate member
2368/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002369void
Douglas Gregor6b906862009-08-21 00:16:32 +00002370Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2371 bool HasExplicitTemplateArgs,
2372 const TemplateArgument *ExplicitTemplateArgs,
2373 unsigned NumExplicitTemplateArgs,
2374 Expr *Object, Expr **Args, unsigned NumArgs,
2375 OverloadCandidateSet& CandidateSet,
2376 bool SuppressUserConversions,
2377 bool ForceRValue) {
2378 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002379 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00002380 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002381 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00002382 // candidate functions in the usual way.113) A given name can refer to one
2383 // or more function templates and also to a set of overloaded non-template
2384 // functions. In such a case, the candidate functions generated from each
2385 // function template are combined with the set of non-template candidate
2386 // functions.
2387 TemplateDeductionInfo Info(Context);
2388 FunctionDecl *Specialization = 0;
2389 if (TemplateDeductionResult Result
2390 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2391 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2392 Args, NumArgs, Specialization, Info)) {
2393 // FIXME: Record what happened with template argument deduction, so
2394 // that we can give the user a beautiful diagnostic.
2395 (void)Result;
2396 return;
2397 }
Mike Stump1eb44332009-09-09 15:08:12 +00002398
Douglas Gregor6b906862009-08-21 00:16:32 +00002399 // Add the function template specialization produced by template argument
2400 // deduction as a candidate.
2401 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00002402 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00002403 "Specialization is not a member function?");
Mike Stump1eb44332009-09-09 15:08:12 +00002404 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002405 CandidateSet, SuppressUserConversions, ForceRValue);
2406}
2407
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002408/// \brief Add a C++ function template specialization as a candidate
2409/// in the candidate set, using template argument deduction to produce
2410/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002411void
Douglas Gregore53060f2009-06-25 22:08:12 +00002412Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002413 bool HasExplicitTemplateArgs,
2414 const TemplateArgument *ExplicitTemplateArgs,
2415 unsigned NumExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002416 Expr **Args, unsigned NumArgs,
2417 OverloadCandidateSet& CandidateSet,
2418 bool SuppressUserConversions,
2419 bool ForceRValue) {
2420 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002421 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00002422 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002423 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00002424 // candidate functions in the usual way.113) A given name can refer to one
2425 // or more function templates and also to a set of overloaded non-template
2426 // functions. In such a case, the candidate functions generated from each
2427 // function template are combined with the set of non-template candidate
2428 // functions.
2429 TemplateDeductionInfo Info(Context);
2430 FunctionDecl *Specialization = 0;
2431 if (TemplateDeductionResult Result
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002432 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2433 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2434 Args, NumArgs, Specialization, Info)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002435 // FIXME: Record what happened with template argument deduction, so
2436 // that we can give the user a beautiful diagnostic.
2437 (void)Result;
2438 return;
2439 }
Mike Stump1eb44332009-09-09 15:08:12 +00002440
Douglas Gregore53060f2009-06-25 22:08:12 +00002441 // Add the function template specialization produced by template argument
2442 // deduction as a candidate.
2443 assert(Specialization && "Missing function template specialization?");
2444 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2445 SuppressUserConversions, ForceRValue);
2446}
Mike Stump1eb44332009-09-09 15:08:12 +00002447
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002448/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00002449/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002450/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00002451/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002452/// (which may or may not be the same type as the type that the
2453/// conversion function produces).
2454void
2455Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2456 Expr *From, QualType ToType,
2457 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002458 assert(!Conversion->getDescribedFunctionTemplate() &&
2459 "Conversion function templates use AddTemplateConversionCandidate");
2460
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002461 // Add this candidate
2462 CandidateSet.push_back(OverloadCandidate());
2463 OverloadCandidate& Candidate = CandidateSet.back();
2464 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002465 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002466 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002467 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump1eb44332009-09-09 15:08:12 +00002468 Candidate.FinalConversion.FromTypePtr
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002469 = Conversion->getConversionType().getAsOpaquePtr();
2470 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2471
Douglas Gregor96176b32008-11-18 23:14:02 +00002472 // Determine the implicit conversion sequence for the implicit
2473 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002474 Candidate.Viable = true;
2475 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00002476 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002477 // Conversion functions to a different type in the base class is visible in
2478 // the derived class. So, a derived to base conversion should not participate
2479 // in overload resolution.
2480 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2481 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump1eb44332009-09-09 15:08:12 +00002482 if (Candidate.Conversions[0].ConversionKind
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002483 == ImplicitConversionSequence::BadConversion) {
2484 Candidate.Viable = false;
2485 return;
2486 }
2487
2488 // To determine what the conversion from the result of calling the
2489 // conversion function to the type we're eventually trying to
2490 // convert to (ToType), we need to synthesize a call to the
2491 // conversion function and attempt copy initialization from it. This
2492 // makes sure that we get the right semantics with respect to
2493 // lvalues/rvalues and the type. Fortunately, we can allocate this
2494 // call on the stack and we don't need its arguments to be
2495 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00002496 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002497 SourceLocation());
2498 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002499 CastExpr::CK_Unknown,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002500 &ConversionRef, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002501
2502 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00002503 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2504 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00002505 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002506 Conversion->getConversionType().getNonReferenceType(),
2507 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002508 ImplicitConversionSequence ICS =
2509 TryCopyInitialization(&Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002510 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002511 /*ForceRValue=*/false,
2512 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002513
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002514 switch (ICS.ConversionKind) {
2515 case ImplicitConversionSequence::StandardConversion:
2516 Candidate.FinalConversion = ICS.Standard;
2517 break;
2518
2519 case ImplicitConversionSequence::BadConversion:
2520 Candidate.Viable = false;
2521 break;
2522
2523 default:
Mike Stump1eb44332009-09-09 15:08:12 +00002524 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002525 "Can only end up with a standard conversion sequence or failure");
2526 }
2527}
2528
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002529/// \brief Adds a conversion function template specialization
2530/// candidate to the overload set, using template argument deduction
2531/// to deduce the template arguments of the conversion function
2532/// template from the type that we are converting to (C++
2533/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00002534void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002535Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2536 Expr *From, QualType ToType,
2537 OverloadCandidateSet &CandidateSet) {
2538 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2539 "Only conversion function templates permitted here");
2540
2541 TemplateDeductionInfo Info(Context);
2542 CXXConversionDecl *Specialization = 0;
2543 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00002544 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002545 Specialization, Info)) {
2546 // FIXME: Record what happened with template argument deduction, so
2547 // that we can give the user a beautiful diagnostic.
2548 (void)Result;
2549 return;
2550 }
Mike Stump1eb44332009-09-09 15:08:12 +00002551
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002552 // Add the conversion function template specialization produced by
2553 // template argument deduction as a candidate.
2554 assert(Specialization && "Missing function template specialization?");
2555 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2556}
2557
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002558/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2559/// converts the given @c Object to a function pointer via the
2560/// conversion function @c Conversion, and then attempts to call it
2561/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2562/// the type of function that we'll eventually be calling.
2563void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor72564e72009-02-26 23:50:07 +00002564 const FunctionProtoType *Proto,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002565 Expr *Object, Expr **Args, unsigned NumArgs,
2566 OverloadCandidateSet& CandidateSet) {
2567 CandidateSet.push_back(OverloadCandidate());
2568 OverloadCandidate& Candidate = CandidateSet.back();
2569 Candidate.Function = 0;
2570 Candidate.Surrogate = Conversion;
2571 Candidate.Viable = true;
2572 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002573 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002574 Candidate.Conversions.resize(NumArgs + 1);
2575
2576 // Determine the implicit conversion sequence for the implicit
2577 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00002578 ImplicitConversionSequence ObjectInit
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002579 = TryObjectArgumentInitialization(Object, Conversion);
2580 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2581 Candidate.Viable = false;
2582 return;
2583 }
2584
2585 // The first conversion is actually a user-defined conversion whose
2586 // first conversion is ObjectInit's standard conversion (which is
2587 // effectively a reference binding). Record it as such.
Mike Stump1eb44332009-09-09 15:08:12 +00002588 Candidate.Conversions[0].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002589 = ImplicitConversionSequence::UserDefinedConversion;
2590 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2591 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00002592 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002593 = Candidate.Conversions[0].UserDefined.Before;
2594 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2595
Mike Stump1eb44332009-09-09 15:08:12 +00002596 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002597 unsigned NumArgsInProto = Proto->getNumArgs();
2598
2599 // (C++ 13.3.2p2): A candidate function having fewer than m
2600 // parameters is viable only if it has an ellipsis in its parameter
2601 // list (8.3.5).
2602 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2603 Candidate.Viable = false;
2604 return;
2605 }
2606
2607 // Function types don't have any default arguments, so just check if
2608 // we have enough arguments.
2609 if (NumArgs < NumArgsInProto) {
2610 // Not enough arguments.
2611 Candidate.Viable = false;
2612 return;
2613 }
2614
2615 // Determine the implicit conversion sequences for each of the
2616 // arguments.
2617 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2618 if (ArgIdx < NumArgsInProto) {
2619 // (C++ 13.3.2p3): for F to be a viable function, there shall
2620 // exist for each argument an implicit conversion sequence
2621 // (13.3.3.1) that converts that argument to the corresponding
2622 // parameter of F.
2623 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002624 Candidate.Conversions[ArgIdx + 1]
2625 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002626 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002627 /*ForceRValue=*/false,
2628 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002629 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002630 == ImplicitConversionSequence::BadConversion) {
2631 Candidate.Viable = false;
2632 break;
2633 }
2634 } else {
2635 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2636 // argument for which there is no corresponding parameter is
2637 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002638 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002639 = ImplicitConversionSequence::EllipsisConversion;
2640 }
2641 }
2642}
2643
Mike Stump390b4cc2009-05-16 07:39:55 +00002644// FIXME: This will eventually be removed, once we've migrated all of the
2645// operator overloading logic over to the scheme used by binary operators, which
2646// works for template instantiation.
Douglas Gregor063daf62009-03-13 18:40:31 +00002647void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002648 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00002649 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002650 OverloadCandidateSet& CandidateSet,
2651 SourceRange OpRange) {
Douglas Gregor063daf62009-03-13 18:40:31 +00002652
2653 FunctionSet Functions;
2654
2655 QualType T1 = Args[0]->getType();
2656 QualType T2;
2657 if (NumArgs > 1)
2658 T2 = Args[1]->getType();
2659
2660 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002661 if (S)
2662 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00002663 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2664 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2665 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2666 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2667}
2668
2669/// \brief Add overload candidates for overloaded operators that are
2670/// member functions.
2671///
2672/// Add the overloaded operator candidates that are member functions
2673/// for the operator Op that was used in an operator expression such
2674/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2675/// CandidateSet will store the added overload candidates. (C++
2676/// [over.match.oper]).
2677void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2678 SourceLocation OpLoc,
2679 Expr **Args, unsigned NumArgs,
2680 OverloadCandidateSet& CandidateSet,
2681 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002682 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2683
2684 // C++ [over.match.oper]p3:
2685 // For a unary operator @ with an operand of a type whose
2686 // cv-unqualified version is T1, and for a binary operator @ with
2687 // a left operand of a type whose cv-unqualified version is T1 and
2688 // a right operand of a type whose cv-unqualified version is T2,
2689 // three sets of candidate functions, designated member
2690 // candidates, non-member candidates and built-in candidates, are
2691 // constructed as follows:
2692 QualType T1 = Args[0]->getType();
2693 QualType T2;
2694 if (NumArgs > 1)
2695 T2 = Args[1]->getType();
2696
2697 // -- If T1 is a class type, the set of member candidates is the
2698 // result of the qualified lookup of T1::operator@
2699 // (13.3.1.1.1); otherwise, the set of member candidates is
2700 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00002701 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002702 // Complete the type if it can be completed. Otherwise, we're done.
2703 if (RequireCompleteType(OpLoc, T1, PartialDiagnostic(0)))
2704 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002705
2706 LookupResult Operators = LookupQualifiedName(T1Rec->getDecl(), OpName,
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002707 LookupOrdinaryName, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002708 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002709 OperEnd = Operators.end();
2710 Oper != OperEnd;
2711 ++Oper)
Mike Stump1eb44332009-09-09 15:08:12 +00002712 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002713 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor96176b32008-11-18 23:14:02 +00002714 /*SuppressUserConversions=*/false);
Douglas Gregor96176b32008-11-18 23:14:02 +00002715 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002716}
2717
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002718/// AddBuiltinCandidate - Add a candidate for a built-in
2719/// operator. ResultTy and ParamTys are the result and parameter types
2720/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002721/// arguments being passed to the candidate. IsAssignmentOperator
2722/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002723/// operator. NumContextualBoolArguments is the number of arguments
2724/// (at the beginning of the argument list) that will be contextually
2725/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00002726void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002727 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002728 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002729 bool IsAssignmentOperator,
2730 unsigned NumContextualBoolArguments) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002731 // Add this candidate
2732 CandidateSet.push_back(OverloadCandidate());
2733 OverloadCandidate& Candidate = CandidateSet.back();
2734 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00002735 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002736 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002737 Candidate.BuiltinTypes.ResultTy = ResultTy;
2738 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2739 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2740
2741 // Determine the implicit conversion sequences for each of the
2742 // arguments.
2743 Candidate.Viable = true;
2744 Candidate.Conversions.resize(NumArgs);
2745 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002746 // C++ [over.match.oper]p4:
2747 // For the built-in assignment operators, conversions of the
2748 // left operand are restricted as follows:
2749 // -- no temporaries are introduced to hold the left operand, and
2750 // -- no user-defined conversions are applied to the left
2751 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00002752 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002753 //
2754 // We block these conversions by turning off user-defined
2755 // conversions, since that is the only way that initialization of
2756 // a reference to a non-class type can occur from something that
2757 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002758 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00002759 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002760 "Contextual conversion to bool requires bool type");
2761 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2762 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002763 Candidate.Conversions[ArgIdx]
2764 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00002765 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002766 /*ForceRValue=*/false,
2767 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002768 }
Mike Stump1eb44332009-09-09 15:08:12 +00002769 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002770 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002771 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002772 break;
2773 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002774 }
2775}
2776
2777/// BuiltinCandidateTypeSet - A set of types that will be used for the
2778/// candidate operator functions for built-in operators (C++
2779/// [over.built]). The types are separated into pointer types and
2780/// enumeration types.
2781class BuiltinCandidateTypeSet {
2782 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002783 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002784
2785 /// PointerTypes - The set of pointer types that will be used in the
2786 /// built-in candidates.
2787 TypeSet PointerTypes;
2788
Sebastian Redl78eb8742009-04-19 21:53:20 +00002789 /// MemberPointerTypes - The set of member pointer types that will be
2790 /// used in the built-in candidates.
2791 TypeSet MemberPointerTypes;
2792
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002793 /// EnumerationTypes - The set of enumeration types that will be
2794 /// used in the built-in candidates.
2795 TypeSet EnumerationTypes;
2796
Douglas Gregor5842ba92009-08-24 15:23:48 +00002797 /// Sema - The semantic analysis instance where we are building the
2798 /// candidate type set.
2799 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00002800
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002801 /// Context - The AST context in which we will build the type sets.
2802 ASTContext &Context;
2803
Sebastian Redl78eb8742009-04-19 21:53:20 +00002804 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2805 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002806
2807public:
2808 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002809 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002810
Mike Stump1eb44332009-09-09 15:08:12 +00002811 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00002812 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002813
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002814 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2815 bool AllowExplicitConversions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002816
2817 /// pointer_begin - First pointer type found;
2818 iterator pointer_begin() { return PointerTypes.begin(); }
2819
Sebastian Redl78eb8742009-04-19 21:53:20 +00002820 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002821 iterator pointer_end() { return PointerTypes.end(); }
2822
Sebastian Redl78eb8742009-04-19 21:53:20 +00002823 /// member_pointer_begin - First member pointer type found;
2824 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2825
2826 /// member_pointer_end - Past the last member pointer type found;
2827 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2828
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002829 /// enumeration_begin - First enumeration type found;
2830 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2831
Sebastian Redl78eb8742009-04-19 21:53:20 +00002832 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002833 iterator enumeration_end() { return EnumerationTypes.end(); }
2834};
2835
Sebastian Redl78eb8742009-04-19 21:53:20 +00002836/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002837/// the set of pointer types along with any more-qualified variants of
2838/// that type. For example, if @p Ty is "int const *", this routine
2839/// will add "int const *", "int const volatile *", "int const
2840/// restrict *", and "int const volatile restrict *" to the set of
2841/// pointer types. Returns true if the add of @p Ty itself succeeded,
2842/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00002843///
2844/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00002845bool
2846BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
John McCall0953e762009-09-24 19:53:00 +00002847
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002848 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002849 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002850 return false;
2851
John McCall0953e762009-09-24 19:53:00 +00002852 const PointerType *PointerTy = Ty->getAs<PointerType>();
2853 assert(PointerTy && "type was not a pointer type!");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002854
John McCall0953e762009-09-24 19:53:00 +00002855 QualType PointeeTy = PointerTy->getPointeeType();
2856 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
2857
2858 // Iterate through all strict supersets of BaseCVR.
2859 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
2860 if ((CVR | BaseCVR) != CVR) continue;
2861
2862 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
2863 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002864 }
2865
2866 return true;
2867}
2868
Sebastian Redl78eb8742009-04-19 21:53:20 +00002869/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2870/// to the set of pointer types along with any more-qualified variants of
2871/// that type. For example, if @p Ty is "int const *", this routine
2872/// will add "int const *", "int const volatile *", "int const
2873/// restrict *", and "int const volatile restrict *" to the set of
2874/// pointer types. Returns true if the add of @p Ty itself succeeded,
2875/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00002876///
2877/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00002878bool
2879BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2880 QualType Ty) {
2881 // Insert this type.
2882 if (!MemberPointerTypes.insert(Ty))
2883 return false;
2884
John McCall0953e762009-09-24 19:53:00 +00002885 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
2886 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00002887
John McCall0953e762009-09-24 19:53:00 +00002888 QualType PointeeTy = PointerTy->getPointeeType();
2889 const Type *ClassTy = PointerTy->getClass();
2890
2891 // Iterate through all strict supersets of the pointee type's CVR
2892 // qualifiers.
2893 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
2894 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
2895 if ((CVR | BaseCVR) != CVR) continue;
2896
2897 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
2898 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00002899 }
2900
2901 return true;
2902}
2903
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002904/// AddTypesConvertedFrom - Add each of the types to which the type @p
2905/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00002906/// primarily interested in pointer types and enumeration types. We also
2907/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002908/// AllowUserConversions is true if we should look at the conversion
2909/// functions of a class type, and AllowExplicitConversions if we
2910/// should also include the explicit conversion functions of a class
2911/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00002912void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002913BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2914 bool AllowUserConversions,
2915 bool AllowExplicitConversions) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002916 // Only deal with canonical types.
2917 Ty = Context.getCanonicalType(Ty);
2918
2919 // Look through reference types; they aren't part of the type of an
2920 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00002921 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002922 Ty = RefTy->getPointeeType();
2923
2924 // We don't care about qualifiers on the type.
2925 Ty = Ty.getUnqualifiedType();
2926
Ted Kremenek6217b802009-07-29 21:53:49 +00002927 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002928 QualType PointeeTy = PointerTy->getPointeeType();
2929
2930 // Insert our type, and its more-qualified variants, into the set
2931 // of types.
Sebastian Redl78eb8742009-04-19 21:53:20 +00002932 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002933 return;
2934
2935 // Add 'cv void*' to our set of types.
2936 if (!Ty->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002937 QualType QualVoid
John McCall0953e762009-09-24 19:53:00 +00002938 = Context.getCVRQualifiedType(Context.VoidTy,
2939 PointeeTy.getCVRQualifiers());
Sebastian Redl78eb8742009-04-19 21:53:20 +00002940 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002941 }
2942
2943 // If this is a pointer to a class type, add pointers to its bases
2944 // (with the same level of cv-qualification as the original
2945 // derived class, of course).
Ted Kremenek6217b802009-07-29 21:53:49 +00002946 if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002947 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2948 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2949 Base != ClassDecl->bases_end(); ++Base) {
2950 QualType BaseTy = Context.getCanonicalType(Base->getType());
John McCall0953e762009-09-24 19:53:00 +00002951 BaseTy = Context.getCVRQualifiedType(BaseTy.getUnqualifiedType(),
2952 PointeeTy.getCVRQualifiers());
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002953
2954 // Add the pointer type, recursively, so that we get all of
2955 // the indirect base classes, too.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002956 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002957 }
2958 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00002959 } else if (Ty->isMemberPointerType()) {
2960 // Member pointers are far easier, since the pointee can't be converted.
2961 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2962 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002963 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00002964 EnumerationTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002965 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002966 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002967 if (SemaRef.RequireCompleteType(SourceLocation(), Ty, 0)) {
2968 // No conversion functions in incomplete types.
2969 return;
2970 }
Mike Stump1eb44332009-09-09 15:08:12 +00002971
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002972 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2973 // FIXME: Visit conversion functions in the base classes, too.
Mike Stump1eb44332009-09-09 15:08:12 +00002974 OverloadedFunctionDecl *Conversions
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002975 = ClassDecl->getConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00002976 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002977 = Conversions->function_begin();
2978 Func != Conversions->function_end(); ++Func) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002979 CXXConversionDecl *Conv;
2980 FunctionTemplateDecl *ConvTemplate;
2981 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
2982
Mike Stump1eb44332009-09-09 15:08:12 +00002983 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002984 // about which builtin types we can convert to.
2985 if (ConvTemplate)
2986 continue;
2987
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002988 if (AllowExplicitConversions || !Conv->isExplicit())
2989 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002990 }
2991 }
2992 }
2993}
2994
Douglas Gregor19b7b152009-08-24 13:43:27 +00002995/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
2996/// the volatile- and non-volatile-qualified assignment operators for the
2997/// given type to the candidate set.
2998static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
2999 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00003000 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003001 unsigned NumArgs,
3002 OverloadCandidateSet &CandidateSet) {
3003 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00003004
Douglas Gregor19b7b152009-08-24 13:43:27 +00003005 // T& operator=(T&, T)
3006 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3007 ParamTypes[1] = T;
3008 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3009 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003010
Douglas Gregor19b7b152009-08-24 13:43:27 +00003011 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3012 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00003013 ParamTypes[0]
3014 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00003015 ParamTypes[1] = T;
3016 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00003017 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003018 }
3019}
Mike Stump1eb44332009-09-09 15:08:12 +00003020
Douglas Gregor74253732008-11-19 15:42:04 +00003021/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3022/// operator overloads to the candidate set (C++ [over.built]), based
3023/// on the operator @p Op and the arguments given. For example, if the
3024/// operator is a binary '+', this routine might add "int
3025/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003026void
Mike Stump1eb44332009-09-09 15:08:12 +00003027Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor74253732008-11-19 15:42:04 +00003028 Expr **Args, unsigned NumArgs,
3029 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003030 // The set of "promoted arithmetic types", which are the arithmetic
3031 // types are that preserved by promotion (C++ [over.built]p2). Note
3032 // that the first few of these types are the promoted integral
3033 // types; these types need to be first.
3034 // FIXME: What about complex?
3035 const unsigned FirstIntegralType = 0;
3036 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00003037 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003038 LastPromotedIntegralType = 13;
3039 const unsigned FirstPromotedArithmeticType = 7,
3040 LastPromotedArithmeticType = 16;
3041 const unsigned NumArithmeticTypes = 16;
3042 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00003043 Context.BoolTy, Context.CharTy, Context.WCharTy,
3044// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003045 Context.SignedCharTy, Context.ShortTy,
3046 Context.UnsignedCharTy, Context.UnsignedShortTy,
3047 Context.IntTy, Context.LongTy, Context.LongLongTy,
3048 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3049 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3050 };
3051
3052 // Find all of the types that the arguments can convert to, but only
3053 // if the operator we're looking at has built-in operator candidates
3054 // that make use of these types.
Douglas Gregor5842ba92009-08-24 15:23:48 +00003055 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003056 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3057 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00003058 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003059 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00003060 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003061 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor74253732008-11-19 15:42:04 +00003062 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003063 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3064 true,
3065 (Op == OO_Exclaim ||
3066 Op == OO_AmpAmp ||
3067 Op == OO_PipePipe));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003068 }
3069
3070 bool isComparison = false;
3071 switch (Op) {
3072 case OO_None:
3073 case NUM_OVERLOADED_OPERATORS:
3074 assert(false && "Expected an overloaded operator");
3075 break;
3076
Douglas Gregor74253732008-11-19 15:42:04 +00003077 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00003078 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00003079 goto UnaryStar;
3080 else
3081 goto BinaryStar;
3082 break;
3083
3084 case OO_Plus: // '+' is either unary or binary
3085 if (NumArgs == 1)
3086 goto UnaryPlus;
3087 else
3088 goto BinaryPlus;
3089 break;
3090
3091 case OO_Minus: // '-' is either unary or binary
3092 if (NumArgs == 1)
3093 goto UnaryMinus;
3094 else
3095 goto BinaryMinus;
3096 break;
3097
3098 case OO_Amp: // '&' is either unary or binary
3099 if (NumArgs == 1)
3100 goto UnaryAmp;
3101 else
3102 goto BinaryAmp;
3103
3104 case OO_PlusPlus:
3105 case OO_MinusMinus:
3106 // C++ [over.built]p3:
3107 //
3108 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3109 // is either volatile or empty, there exist candidate operator
3110 // functions of the form
3111 //
3112 // VQ T& operator++(VQ T&);
3113 // T operator++(VQ T&, int);
3114 //
3115 // C++ [over.built]p4:
3116 //
3117 // For every pair (T, VQ), where T is an arithmetic type other
3118 // than bool, and VQ is either volatile or empty, there exist
3119 // candidate operator functions of the form
3120 //
3121 // VQ T& operator--(VQ T&);
3122 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00003123 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00003124 Arith < NumArithmeticTypes; ++Arith) {
3125 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00003126 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003127 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00003128
3129 // Non-volatile version.
3130 if (NumArgs == 1)
3131 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3132 else
3133 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3134
3135 // Volatile version
John McCall0953e762009-09-24 19:53:00 +00003136 ParamTypes[0]
3137 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
Douglas Gregor74253732008-11-19 15:42:04 +00003138 if (NumArgs == 1)
3139 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3140 else
3141 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3142 }
3143
3144 // C++ [over.built]p5:
3145 //
3146 // For every pair (T, VQ), where T is a cv-qualified or
3147 // cv-unqualified object type, and VQ is either volatile or
3148 // empty, there exist candidate operator functions of the form
3149 //
3150 // T*VQ& operator++(T*VQ&);
3151 // T*VQ& operator--(T*VQ&);
3152 // T* operator++(T*VQ&, int);
3153 // T* operator--(T*VQ&, int);
3154 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3155 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3156 // Skip pointer types that aren't pointers to object types.
Ted Kremenek6217b802009-07-29 21:53:49 +00003157 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00003158 continue;
3159
Mike Stump1eb44332009-09-09 15:08:12 +00003160 QualType ParamTypes[2] = {
3161 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00003162 };
Mike Stump1eb44332009-09-09 15:08:12 +00003163
Douglas Gregor74253732008-11-19 15:42:04 +00003164 // Without volatile
3165 if (NumArgs == 1)
3166 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3167 else
3168 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3169
3170 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3171 // With volatile
John McCall0953e762009-09-24 19:53:00 +00003172 ParamTypes[0]
3173 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00003174 if (NumArgs == 1)
3175 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3176 else
3177 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3178 }
3179 }
3180 break;
3181
3182 UnaryStar:
3183 // C++ [over.built]p6:
3184 // For every cv-qualified or cv-unqualified object type T, there
3185 // exist candidate operator functions of the form
3186 //
3187 // T& operator*(T*);
3188 //
3189 // C++ [over.built]p7:
3190 // For every function type T, there exist candidate operator
3191 // functions of the form
3192 // T& operator*(T*);
3193 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3194 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3195 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00003196 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003197 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00003198 &ParamTy, Args, 1, CandidateSet);
3199 }
3200 break;
3201
3202 UnaryPlus:
3203 // C++ [over.built]p8:
3204 // For every type T, there exist candidate operator functions of
3205 // the form
3206 //
3207 // T* operator+(T*);
3208 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3209 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3210 QualType ParamTy = *Ptr;
3211 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3212 }
Mike Stump1eb44332009-09-09 15:08:12 +00003213
Douglas Gregor74253732008-11-19 15:42:04 +00003214 // Fall through
3215
3216 UnaryMinus:
3217 // C++ [over.built]p9:
3218 // For every promoted arithmetic type T, there exist candidate
3219 // operator functions of the form
3220 //
3221 // T operator+(T);
3222 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003223 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00003224 Arith < LastPromotedArithmeticType; ++Arith) {
3225 QualType ArithTy = ArithmeticTypes[Arith];
3226 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3227 }
3228 break;
3229
3230 case OO_Tilde:
3231 // C++ [over.built]p10:
3232 // For every promoted integral type T, there exist candidate
3233 // operator functions of the form
3234 //
3235 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003236 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00003237 Int < LastPromotedIntegralType; ++Int) {
3238 QualType IntTy = ArithmeticTypes[Int];
3239 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3240 }
3241 break;
3242
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003243 case OO_New:
3244 case OO_Delete:
3245 case OO_Array_New:
3246 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003247 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00003248 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003249 break;
3250
3251 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00003252 UnaryAmp:
3253 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003254 // C++ [over.match.oper]p3:
3255 // -- For the operator ',', the unary operator '&', or the
3256 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003257 break;
3258
Douglas Gregor19b7b152009-08-24 13:43:27 +00003259 case OO_EqualEqual:
3260 case OO_ExclaimEqual:
3261 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00003262 // For every pointer to member type T, there exist candidate operator
3263 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00003264 //
3265 // bool operator==(T,T);
3266 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00003267 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00003268 MemPtr = CandidateTypes.member_pointer_begin(),
3269 MemPtrEnd = CandidateTypes.member_pointer_end();
3270 MemPtr != MemPtrEnd;
3271 ++MemPtr) {
3272 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3273 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3274 }
Mike Stump1eb44332009-09-09 15:08:12 +00003275
Douglas Gregor19b7b152009-08-24 13:43:27 +00003276 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00003277
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003278 case OO_Less:
3279 case OO_Greater:
3280 case OO_LessEqual:
3281 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003282 // C++ [over.built]p15:
3283 //
3284 // For every pointer or enumeration type T, there exist
3285 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003286 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003287 // bool operator<(T, T);
3288 // bool operator>(T, T);
3289 // bool operator<=(T, T);
3290 // bool operator>=(T, T);
3291 // bool operator==(T, T);
3292 // bool operator!=(T, T);
3293 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3294 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3295 QualType ParamTypes[2] = { *Ptr, *Ptr };
3296 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3297 }
Mike Stump1eb44332009-09-09 15:08:12 +00003298 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003299 = CandidateTypes.enumeration_begin();
3300 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3301 QualType ParamTypes[2] = { *Enum, *Enum };
3302 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3303 }
3304
3305 // Fall through.
3306 isComparison = true;
3307
Douglas Gregor74253732008-11-19 15:42:04 +00003308 BinaryPlus:
3309 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003310 if (!isComparison) {
3311 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3312
3313 // C++ [over.built]p13:
3314 //
3315 // For every cv-qualified or cv-unqualified object type T
3316 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003317 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003318 // T* operator+(T*, ptrdiff_t);
3319 // T& operator[](T*, ptrdiff_t); [BELOW]
3320 // T* operator-(T*, ptrdiff_t);
3321 // T* operator+(ptrdiff_t, T*);
3322 // T& operator[](ptrdiff_t, T*); [BELOW]
3323 //
3324 // C++ [over.built]p14:
3325 //
3326 // For every T, where T is a pointer to object type, there
3327 // exist candidate operator functions of the form
3328 //
3329 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00003330 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003331 = CandidateTypes.pointer_begin();
3332 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3333 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3334
3335 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3336 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3337
3338 if (Op == OO_Plus) {
3339 // T* operator+(ptrdiff_t, T*);
3340 ParamTypes[0] = ParamTypes[1];
3341 ParamTypes[1] = *Ptr;
3342 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3343 } else {
3344 // ptrdiff_t operator-(T, T);
3345 ParamTypes[1] = *Ptr;
3346 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3347 Args, 2, CandidateSet);
3348 }
3349 }
3350 }
3351 // Fall through
3352
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003353 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00003354 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003355 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003356 // C++ [over.built]p12:
3357 //
3358 // For every pair of promoted arithmetic types L and R, there
3359 // exist candidate operator functions of the form
3360 //
3361 // LR operator*(L, R);
3362 // LR operator/(L, R);
3363 // LR operator+(L, R);
3364 // LR operator-(L, R);
3365 // bool operator<(L, R);
3366 // bool operator>(L, R);
3367 // bool operator<=(L, R);
3368 // bool operator>=(L, R);
3369 // bool operator==(L, R);
3370 // bool operator!=(L, R);
3371 //
3372 // where LR is the result of the usual arithmetic conversions
3373 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003374 //
3375 // C++ [over.built]p24:
3376 //
3377 // For every pair of promoted arithmetic types L and R, there exist
3378 // candidate operator functions of the form
3379 //
3380 // LR operator?(bool, L, R);
3381 //
3382 // where LR is the result of the usual arithmetic conversions
3383 // between types L and R.
3384 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003385 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003386 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003387 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003388 Right < LastPromotedArithmeticType; ++Right) {
3389 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00003390 QualType Result
3391 = isComparison
3392 ? Context.BoolTy
3393 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003394 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3395 }
3396 }
3397 break;
3398
3399 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00003400 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003401 case OO_Caret:
3402 case OO_Pipe:
3403 case OO_LessLess:
3404 case OO_GreaterGreater:
3405 // C++ [over.built]p17:
3406 //
3407 // For every pair of promoted integral types L and R, there
3408 // exist candidate operator functions of the form
3409 //
3410 // LR operator%(L, R);
3411 // LR operator&(L, R);
3412 // LR operator^(L, R);
3413 // LR operator|(L, R);
3414 // L operator<<(L, R);
3415 // L operator>>(L, R);
3416 //
3417 // where LR is the result of the usual arithmetic conversions
3418 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00003419 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003420 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003421 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003422 Right < LastPromotedIntegralType; ++Right) {
3423 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3424 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3425 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00003426 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003427 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3428 }
3429 }
3430 break;
3431
3432 case OO_Equal:
3433 // C++ [over.built]p20:
3434 //
3435 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00003436 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003437 // empty, there exist candidate operator functions of the form
3438 //
3439 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003440 for (BuiltinCandidateTypeSet::iterator
3441 Enum = CandidateTypes.enumeration_begin(),
3442 EnumEnd = CandidateTypes.enumeration_end();
3443 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00003444 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003445 CandidateSet);
3446 for (BuiltinCandidateTypeSet::iterator
3447 MemPtr = CandidateTypes.member_pointer_begin(),
3448 MemPtrEnd = CandidateTypes.member_pointer_end();
3449 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00003450 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003451 CandidateSet);
3452 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003453
3454 case OO_PlusEqual:
3455 case OO_MinusEqual:
3456 // C++ [over.built]p19:
3457 //
3458 // For every pair (T, VQ), where T is any type and VQ is either
3459 // volatile or empty, there exist candidate operator functions
3460 // of the form
3461 //
3462 // T*VQ& operator=(T*VQ&, T*);
3463 //
3464 // C++ [over.built]p21:
3465 //
3466 // For every pair (T, VQ), where T is a cv-qualified or
3467 // cv-unqualified object type and VQ is either volatile or
3468 // empty, there exist candidate operator functions of the form
3469 //
3470 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3471 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3472 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3473 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3474 QualType ParamTypes[2];
3475 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3476
3477 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003478 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003479 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3480 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003481
Douglas Gregor74253732008-11-19 15:42:04 +00003482 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3483 // volatile version
John McCall0953e762009-09-24 19:53:00 +00003484 ParamTypes[0]
3485 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003486 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3487 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003488 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003489 }
3490 // Fall through.
3491
3492 case OO_StarEqual:
3493 case OO_SlashEqual:
3494 // C++ [over.built]p18:
3495 //
3496 // For every triple (L, VQ, R), where L is an arithmetic type,
3497 // VQ is either volatile or empty, and R is a promoted
3498 // arithmetic type, there exist candidate operator functions of
3499 // the form
3500 //
3501 // VQ L& operator=(VQ L&, R);
3502 // VQ L& operator*=(VQ L&, R);
3503 // VQ L& operator/=(VQ L&, R);
3504 // VQ L& operator+=(VQ L&, R);
3505 // VQ L& operator-=(VQ L&, R);
3506 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003507 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003508 Right < LastPromotedArithmeticType; ++Right) {
3509 QualType ParamTypes[2];
3510 ParamTypes[1] = ArithmeticTypes[Right];
3511
3512 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003513 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003514 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3515 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003516
3517 // Add this built-in operator as a candidate (VQ is 'volatile').
John McCall0953e762009-09-24 19:53:00 +00003518 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003519 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003520 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3521 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003522 }
3523 }
3524 break;
3525
3526 case OO_PercentEqual:
3527 case OO_LessLessEqual:
3528 case OO_GreaterGreaterEqual:
3529 case OO_AmpEqual:
3530 case OO_CaretEqual:
3531 case OO_PipeEqual:
3532 // C++ [over.built]p22:
3533 //
3534 // For every triple (L, VQ, R), where L is an integral type, VQ
3535 // is either volatile or empty, and R is a promoted integral
3536 // type, there exist candidate operator functions of the form
3537 //
3538 // VQ L& operator%=(VQ L&, R);
3539 // VQ L& operator<<=(VQ L&, R);
3540 // VQ L& operator>>=(VQ L&, R);
3541 // VQ L& operator&=(VQ L&, R);
3542 // VQ L& operator^=(VQ L&, R);
3543 // VQ L& operator|=(VQ L&, R);
3544 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003545 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003546 Right < LastPromotedIntegralType; ++Right) {
3547 QualType ParamTypes[2];
3548 ParamTypes[1] = ArithmeticTypes[Right];
3549
3550 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003551 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003552 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3553
3554 // Add this built-in operator as a candidate (VQ is 'volatile').
3555 ParamTypes[0] = ArithmeticTypes[Left];
John McCall0953e762009-09-24 19:53:00 +00003556 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003557 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003558 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3559 }
3560 }
3561 break;
3562
Douglas Gregor74253732008-11-19 15:42:04 +00003563 case OO_Exclaim: {
3564 // C++ [over.operator]p23:
3565 //
3566 // There also exist candidate operator functions of the form
3567 //
Mike Stump1eb44332009-09-09 15:08:12 +00003568 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00003569 // bool operator&&(bool, bool); [BELOW]
3570 // bool operator||(bool, bool); [BELOW]
3571 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003572 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3573 /*IsAssignmentOperator=*/false,
3574 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00003575 break;
3576 }
3577
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003578 case OO_AmpAmp:
3579 case OO_PipePipe: {
3580 // C++ [over.operator]p23:
3581 //
3582 // There also exist candidate operator functions of the form
3583 //
Douglas Gregor74253732008-11-19 15:42:04 +00003584 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003585 // bool operator&&(bool, bool);
3586 // bool operator||(bool, bool);
3587 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003588 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3589 /*IsAssignmentOperator=*/false,
3590 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003591 break;
3592 }
3593
3594 case OO_Subscript:
3595 // C++ [over.built]p13:
3596 //
3597 // For every cv-qualified or cv-unqualified object type T there
3598 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003599 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003600 // T* operator+(T*, ptrdiff_t); [ABOVE]
3601 // T& operator[](T*, ptrdiff_t);
3602 // T* operator-(T*, ptrdiff_t); [ABOVE]
3603 // T* operator+(ptrdiff_t, T*); [ABOVE]
3604 // T& operator[](ptrdiff_t, T*);
3605 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3606 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3607 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00003608 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003609 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003610
3611 // T& operator[](T*, ptrdiff_t)
3612 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3613
3614 // T& operator[](ptrdiff_t, T*);
3615 ParamTypes[0] = ParamTypes[1];
3616 ParamTypes[1] = *Ptr;
3617 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3618 }
3619 break;
3620
3621 case OO_ArrowStar:
3622 // FIXME: No support for pointer-to-members yet.
3623 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003624
3625 case OO_Conditional:
3626 // Note that we don't consider the first argument, since it has been
3627 // contextually converted to bool long ago. The candidates below are
3628 // therefore added as binary.
3629 //
3630 // C++ [over.built]p24:
3631 // For every type T, where T is a pointer or pointer-to-member type,
3632 // there exist candidate operator functions of the form
3633 //
3634 // T operator?(bool, T, T);
3635 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003636 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3637 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3638 QualType ParamTypes[2] = { *Ptr, *Ptr };
3639 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3640 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00003641 for (BuiltinCandidateTypeSet::iterator Ptr =
3642 CandidateTypes.member_pointer_begin(),
3643 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3644 QualType ParamTypes[2] = { *Ptr, *Ptr };
3645 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3646 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003647 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003648 }
3649}
3650
Douglas Gregorfa047642009-02-04 00:32:51 +00003651/// \brief Add function candidates found via argument-dependent lookup
3652/// to the set of overloading candidates.
3653///
3654/// This routine performs argument-dependent name lookup based on the
3655/// given function name (which may also be an operator name) and adds
3656/// all of the overload candidates found by ADL to the overload
3657/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00003658void
Douglas Gregorfa047642009-02-04 00:32:51 +00003659Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3660 Expr **Args, unsigned NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003661 bool HasExplicitTemplateArgs,
3662 const TemplateArgument *ExplicitTemplateArgs,
3663 unsigned NumExplicitTemplateArgs,
3664 OverloadCandidateSet& CandidateSet,
3665 bool PartialOverloading) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003666 FunctionSet Functions;
Douglas Gregorfa047642009-02-04 00:32:51 +00003667
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003668 // FIXME: Should we be trafficking in canonical function decls throughout?
3669
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003670 // Record all of the function candidates that we've already
3671 // added to the overload set, so that we don't add those same
3672 // candidates a second time.
3673 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3674 CandEnd = CandidateSet.end();
3675 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00003676 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003677 Functions.insert(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00003678 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3679 Functions.insert(FunTmpl);
3680 }
Douglas Gregorfa047642009-02-04 00:32:51 +00003681
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003682 // FIXME: Pass in the explicit template arguments?
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003683 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregorfa047642009-02-04 00:32:51 +00003684
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003685 // Erase all of the candidates we already knew about.
3686 // FIXME: This is suboptimal. Is there a better way?
3687 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3688 CandEnd = CandidateSet.end();
3689 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00003690 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003691 Functions.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00003692 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3693 Functions.erase(FunTmpl);
3694 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003695
3696 // For each of the ADL candidates we found, add it to the overload
3697 // set.
3698 for (FunctionSet::iterator Func = Functions.begin(),
3699 FuncEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00003700 Func != FuncEnd; ++Func) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003701 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
3702 if (HasExplicitTemplateArgs)
3703 continue;
3704
3705 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
3706 false, false, PartialOverloading);
3707 } else
Mike Stump1eb44332009-09-09 15:08:12 +00003708 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003709 HasExplicitTemplateArgs,
3710 ExplicitTemplateArgs,
3711 NumExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003712 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00003713 }
Douglas Gregorfa047642009-02-04 00:32:51 +00003714}
3715
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003716/// isBetterOverloadCandidate - Determines whether the first overload
3717/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00003718bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003719Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump1eb44332009-09-09 15:08:12 +00003720 const OverloadCandidate& Cand2) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003721 // Define viable functions to be better candidates than non-viable
3722 // functions.
3723 if (!Cand2.Viable)
3724 return Cand1.Viable;
3725 else if (!Cand1.Viable)
3726 return false;
3727
Douglas Gregor88a35142008-12-22 05:46:06 +00003728 // C++ [over.match.best]p1:
3729 //
3730 // -- if F is a static member function, ICS1(F) is defined such
3731 // that ICS1(F) is neither better nor worse than ICS1(G) for
3732 // any function G, and, symmetrically, ICS1(G) is neither
3733 // better nor worse than ICS1(F).
3734 unsigned StartArg = 0;
3735 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3736 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003737
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003738 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00003739 // A viable function F1 is defined to be a better function than another
3740 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003741 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003742 unsigned NumArgs = Cand1.Conversions.size();
3743 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3744 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003745 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003746 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3747 Cand2.Conversions[ArgIdx])) {
3748 case ImplicitConversionSequence::Better:
3749 // Cand1 has a better conversion sequence.
3750 HasBetterConversion = true;
3751 break;
3752
3753 case ImplicitConversionSequence::Worse:
3754 // Cand1 can't be better than Cand2.
3755 return false;
3756
3757 case ImplicitConversionSequence::Indistinguishable:
3758 // Do nothing.
3759 break;
3760 }
3761 }
3762
Mike Stump1eb44332009-09-09 15:08:12 +00003763 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003764 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003765 if (HasBetterConversion)
3766 return true;
3767
Mike Stump1eb44332009-09-09 15:08:12 +00003768 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003769 // specialization, or, if not that,
3770 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3771 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3772 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003773
3774 // -- F1 and F2 are function template specializations, and the function
3775 // template for F1 is more specialized than the template for F2
3776 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003777 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00003778 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3779 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003780 if (FunctionTemplateDecl *BetterTemplate
3781 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3782 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor5d7d3752009-09-14 23:02:14 +00003783 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
3784 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003785 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003786
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003787 // -- the context is an initialization by user-defined conversion
3788 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3789 // from the return type of F1 to the destination type (i.e.,
3790 // the type of the entity being initialized) is a better
3791 // conversion sequence than the standard conversion sequence
3792 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00003793 if (Cand1.Function && Cand2.Function &&
3794 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003795 isa<CXXConversionDecl>(Cand2.Function)) {
3796 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3797 Cand2.FinalConversion)) {
3798 case ImplicitConversionSequence::Better:
3799 // Cand1 has a better conversion sequence.
3800 return true;
3801
3802 case ImplicitConversionSequence::Worse:
3803 // Cand1 can't be better than Cand2.
3804 return false;
3805
3806 case ImplicitConversionSequence::Indistinguishable:
3807 // Do nothing
3808 break;
3809 }
3810 }
3811
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003812 return false;
3813}
3814
Mike Stump1eb44332009-09-09 15:08:12 +00003815/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00003816/// within an overload candidate set.
3817///
3818/// \param CandidateSet the set of candidate functions.
3819///
3820/// \param Loc the location of the function name (or operator symbol) for
3821/// which overload resolution occurs.
3822///
Mike Stump1eb44332009-09-09 15:08:12 +00003823/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00003824/// function, Best points to the candidate function found.
3825///
3826/// \returns The result of overload resolution.
Mike Stump1eb44332009-09-09 15:08:12 +00003827Sema::OverloadingResult
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003828Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregore0762c92009-06-19 23:52:42 +00003829 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00003830 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003831 // Find the best viable function.
3832 Best = CandidateSet.end();
3833 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3834 Cand != CandidateSet.end(); ++Cand) {
3835 if (Cand->Viable) {
3836 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3837 Best = Cand;
3838 }
3839 }
3840
3841 // If we didn't find any viable functions, abort.
3842 if (Best == CandidateSet.end())
3843 return OR_No_Viable_Function;
3844
3845 // Make sure that this function is better than every other viable
3846 // function. If not, we have an ambiguity.
3847 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3848 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00003849 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003850 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003851 !isBetterOverloadCandidate(*Best, *Cand)) {
3852 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003853 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003854 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003855 }
Mike Stump1eb44332009-09-09 15:08:12 +00003856
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003857 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003858 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00003859 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003860 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003861 return OR_Deleted;
3862
Douglas Gregore0762c92009-06-19 23:52:42 +00003863 // C++ [basic.def.odr]p2:
3864 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00003865 // when referred to from a potentially-evaluated expression. [Note: this
3866 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00003867 // (clause 13), user-defined conversions (12.3.2), allocation function for
3868 // placement new (5.3.4), as well as non-default initialization (8.5).
3869 if (Best->Function)
3870 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003871 return OR_Success;
3872}
3873
3874/// PrintOverloadCandidates - When overload resolution fails, prints
3875/// diagnostic messages containing the candidates in the candidate
3876/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump1eb44332009-09-09 15:08:12 +00003877void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003878Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00003879 bool OnlyViable) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003880 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3881 LastCand = CandidateSet.end();
3882 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003883 if (Cand->Viable || !OnlyViable) {
3884 if (Cand->Function) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003885 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003886 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003887 // Deleted or "unavailable" function.
3888 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3889 << Cand->Function->isDeleted();
Douglas Gregor1fdd89b2009-09-15 20:11:42 +00003890 } else if (FunctionTemplateDecl *FunTmpl
3891 = Cand->Function->getPrimaryTemplate()) {
3892 // Function template specialization
3893 // FIXME: Give a better reason!
3894 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
3895 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
3896 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003897 } else {
3898 // Normal function
Fariborz Jahanianb1663d02009-09-23 00:58:07 +00003899 bool errReported = false;
3900 if (!Cand->Viable && Cand->Conversions.size() > 0) {
3901 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
3902 const ImplicitConversionSequence &Conversion =
3903 Cand->Conversions[i];
3904 if ((Conversion.ConversionKind !=
3905 ImplicitConversionSequence::BadConversion) ||
3906 Conversion.ConversionFunctionSet.size() == 0)
3907 continue;
3908 Diag(Cand->Function->getLocation(),
3909 diag::err_ovl_candidate_not_viable) << (i+1);
3910 errReported = true;
3911 for (int j = Conversion.ConversionFunctionSet.size()-1;
3912 j >= 0; j--) {
3913 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
3914 Diag(Func->getLocation(), diag::err_ovl_candidate);
3915 }
3916 }
3917 }
3918 if (!errReported)
3919 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003920 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003921 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003922 // Desugar the type of the surrogate down to a function type,
3923 // retaining as many typedefs as possible while still showing
3924 // the function type (and, therefore, its parameter types).
3925 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003926 bool isLValueReference = false;
3927 bool isRValueReference = false;
Douglas Gregor621b3932008-11-21 02:54:28 +00003928 bool isPointer = false;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003929 if (const LValueReferenceType *FnTypeRef =
Ted Kremenek6217b802009-07-29 21:53:49 +00003930 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003931 FnType = FnTypeRef->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003932 isLValueReference = true;
3933 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenek6217b802009-07-29 21:53:49 +00003934 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003935 FnType = FnTypeRef->getPointeeType();
3936 isRValueReference = true;
Douglas Gregor621b3932008-11-21 02:54:28 +00003937 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003938 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003939 FnType = FnTypePtr->getPointeeType();
3940 isPointer = true;
3941 }
3942 // Desugar down to a function type.
John McCall183700f2009-09-21 23:43:11 +00003943 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor621b3932008-11-21 02:54:28 +00003944 // Reconstruct the pointer/reference as appropriate.
3945 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003946 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3947 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor621b3932008-11-21 02:54:28 +00003948
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003949 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003950 << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003951 } else {
3952 // FIXME: We need to get the identifier in here
Mike Stump390b4cc2009-05-16 07:39:55 +00003953 // FIXME: Do we want the error message to point at the operator?
3954 // (built-ins won't have a location)
Mike Stump1eb44332009-09-09 15:08:12 +00003955 QualType FnType
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003956 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3957 Cand->BuiltinTypes.ParamTypes,
3958 Cand->Conversions.size(),
3959 false, 0);
3960
Chris Lattnerd1625842008-11-24 06:25:27 +00003961 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003962 }
3963 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003964 }
3965}
3966
Douglas Gregor904eed32008-11-10 20:40:00 +00003967/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3968/// an overloaded function (C++ [over.over]), where @p From is an
3969/// expression with overloaded function type and @p ToType is the type
3970/// we're trying to resolve to. For example:
3971///
3972/// @code
3973/// int f(double);
3974/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00003975///
Douglas Gregor904eed32008-11-10 20:40:00 +00003976/// int (*pfd)(double) = f; // selects f(double)
3977/// @endcode
3978///
3979/// This routine returns the resulting FunctionDecl if it could be
3980/// resolved, and NULL otherwise. When @p Complain is true, this
3981/// routine will emit diagnostics if there is an error.
3982FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00003983Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor904eed32008-11-10 20:40:00 +00003984 bool Complain) {
3985 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00003986 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00003987 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00003988 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003989 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00003990 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00003991 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00003992 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00003993 FunctionType = MemTypePtr->getPointeeType();
3994 IsMember = true;
3995 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003996
3997 // We only look at pointers or references to functions.
Douglas Gregor72e771f2009-07-09 17:16:51 +00003998 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor83314aa2009-07-08 20:55:45 +00003999 if (!FunctionType->isFunctionType())
Douglas Gregor904eed32008-11-10 20:40:00 +00004000 return 0;
4001
4002 // Find the actual overloaded function declaration.
4003 OverloadedFunctionDecl *Ovl = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004004
Douglas Gregor904eed32008-11-10 20:40:00 +00004005 // C++ [over.over]p1:
4006 // [...] [Note: any redundant set of parentheses surrounding the
4007 // overloaded function name is ignored (5.1). ]
4008 Expr *OvlExpr = From->IgnoreParens();
4009
4010 // C++ [over.over]p1:
4011 // [...] The overloaded function name can be preceded by the &
4012 // operator.
4013 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4014 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4015 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4016 }
4017
4018 // Try to dig out the overloaded function.
Douglas Gregor83314aa2009-07-08 20:55:45 +00004019 FunctionTemplateDecl *FunctionTemplate = 0;
4020 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00004021 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor83314aa2009-07-08 20:55:45 +00004022 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
4023 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004024
Mike Stump1eb44332009-09-09 15:08:12 +00004025 // If there's no overloaded function declaration or function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00004026 // we're done.
4027 if (!Ovl && !FunctionTemplate)
Douglas Gregor904eed32008-11-10 20:40:00 +00004028 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004029
Douglas Gregor83314aa2009-07-08 20:55:45 +00004030 OverloadIterator Fun;
4031 if (Ovl)
4032 Fun = Ovl;
4033 else
4034 Fun = FunctionTemplate;
Mike Stump1eb44332009-09-09 15:08:12 +00004035
Douglas Gregor904eed32008-11-10 20:40:00 +00004036 // Look through all of the overloaded functions, searching for one
4037 // whose type matches exactly.
Douglas Gregor00aeb522009-07-08 23:33:52 +00004038 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004039 bool FoundNonTemplateFunction = false;
Douglas Gregor83314aa2009-07-08 20:55:45 +00004040 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregor904eed32008-11-10 20:40:00 +00004041 // C++ [over.over]p3:
4042 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00004043 // targets of type "pointer-to-function" or "reference-to-function."
4044 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00004045 // type "pointer-to-member-function."
4046 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00004047
Mike Stump1eb44332009-09-09 15:08:12 +00004048 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregor83314aa2009-07-08 20:55:45 +00004049 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004050 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00004051 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004052 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00004053 // static when converting to member pointer.
4054 if (Method->isStatic() == IsMember)
4055 continue;
4056 } else if (IsMember)
4057 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00004058
Douglas Gregor00aeb522009-07-08 23:33:52 +00004059 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004060 // If the name is a function template, template argument deduction is
4061 // done (14.8.2.2), and if the argument deduction succeeds, the
4062 // resulting template argument list is used to generate a single
4063 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00004064 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004065 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00004066 FunctionDecl *Specialization = 0;
4067 TemplateDeductionInfo Info(Context);
4068 if (TemplateDeductionResult Result
4069 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
4070 /*FIXME:*/0, /*FIXME:*/0,
4071 FunctionType, Specialization, Info)) {
4072 // FIXME: make a note of the failed deduction for diagnostics.
4073 (void)Result;
4074 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004075 // FIXME: If the match isn't exact, shouldn't we just drop this as
4076 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00004077 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00004078 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00004079 Matches.insert(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00004080 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor83314aa2009-07-08 20:55:45 +00004081 }
4082 }
Mike Stump1eb44332009-09-09 15:08:12 +00004083
Sebastian Redl33b399a2009-02-04 21:23:32 +00004084 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
4085 // Skip non-static functions when converting to pointer, and static
4086 // when converting to member pointer.
4087 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00004088 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004089 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00004090 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00004091
Douglas Gregore53060f2009-06-25 22:08:12 +00004092 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregor00aeb522009-07-08 23:33:52 +00004093 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00004094 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00004095 FoundNonTemplateFunction = true;
4096 }
Mike Stump1eb44332009-09-09 15:08:12 +00004097 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004098 }
4099
Douglas Gregor00aeb522009-07-08 23:33:52 +00004100 // If there were 0 or 1 matches, we're done.
4101 if (Matches.empty())
4102 return 0;
4103 else if (Matches.size() == 1)
4104 return *Matches.begin();
4105
4106 // C++ [over.over]p4:
4107 // If more than one function is selected, [...]
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004108 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregor312a2022009-09-26 03:56:17 +00004109 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004110 // [...] and any given function template specialization F1 is
4111 // eliminated if the set contains a second function template
4112 // specialization whose function template is more specialized
4113 // than the function template of F1 according to the partial
4114 // ordering rules of 14.5.5.2.
4115
4116 // The algorithm specified above is quadratic. We instead use a
4117 // two-pass algorithm (similar to the one used to identify the
4118 // best viable function in an overload set) that identifies the
4119 // best function template (if it exists).
Douglas Gregor312a2022009-09-26 03:56:17 +00004120 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
4121 Matches.end());
4122 return getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4123 TPOC_Other, From->getLocStart(),
4124 PartialDiagnostic(0),
4125 PartialDiagnostic(diag::err_addr_ovl_ambiguous)
4126 << TemplateMatches[0]->getDeclName(),
4127 PartialDiagnostic(diag::err_ovl_template_candidate));
Douglas Gregor00aeb522009-07-08 23:33:52 +00004128 }
Mike Stump1eb44332009-09-09 15:08:12 +00004129
Douglas Gregor312a2022009-09-26 03:56:17 +00004130 // [...] any function template specializations in the set are
4131 // eliminated if the set also contains a non-template function, [...]
4132 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4133 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4134 if ((*M)->getPrimaryTemplate() == 0)
4135 RemainingMatches.push_back(*M);
4136
Mike Stump1eb44332009-09-09 15:08:12 +00004137 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00004138 // selected function.
4139 if (RemainingMatches.size() == 1)
4140 return RemainingMatches.front();
Mike Stump1eb44332009-09-09 15:08:12 +00004141
Douglas Gregor00aeb522009-07-08 23:33:52 +00004142 // FIXME: We should probably return the same thing that BestViableFunction
4143 // returns (even if we issue the diagnostics here).
4144 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4145 << RemainingMatches[0]->getDeclName();
4146 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4147 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregor904eed32008-11-10 20:40:00 +00004148 return 0;
4149}
4150
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004151/// \brief Add a single candidate to the overload set.
4152static void AddOverloadedCallCandidate(Sema &S,
4153 AnyFunctionDecl Callee,
4154 bool &ArgumentDependentLookup,
4155 bool HasExplicitTemplateArgs,
4156 const TemplateArgument *ExplicitTemplateArgs,
4157 unsigned NumExplicitTemplateArgs,
4158 Expr **Args, unsigned NumArgs,
4159 OverloadCandidateSet &CandidateSet,
4160 bool PartialOverloading) {
4161 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
4162 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
4163 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4164 PartialOverloading);
4165
4166 if (Func->getDeclContext()->isRecord() ||
4167 Func->getDeclContext()->isFunctionOrMethod())
4168 ArgumentDependentLookup = false;
4169 return;
4170 }
4171
4172 FunctionTemplateDecl *FuncTemplate = cast<FunctionTemplateDecl>(Callee);
4173 S.AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4174 ExplicitTemplateArgs,
4175 NumExplicitTemplateArgs,
4176 Args, NumArgs, CandidateSet);
4177
4178 if (FuncTemplate->getDeclContext()->isRecord())
4179 ArgumentDependentLookup = false;
4180}
4181
4182/// \brief Add the overload candidates named by callee and/or found by argument
4183/// dependent lookup to the given overload set.
4184void Sema::AddOverloadedCallCandidates(NamedDecl *Callee,
4185 DeclarationName &UnqualifiedName,
4186 bool &ArgumentDependentLookup,
4187 bool HasExplicitTemplateArgs,
4188 const TemplateArgument *ExplicitTemplateArgs,
4189 unsigned NumExplicitTemplateArgs,
4190 Expr **Args, unsigned NumArgs,
4191 OverloadCandidateSet &CandidateSet,
4192 bool PartialOverloading) {
4193 // Add the functions denoted by Callee to the set of candidate
4194 // functions. While we're doing so, track whether argument-dependent
4195 // lookup still applies, per:
4196 //
4197 // C++0x [basic.lookup.argdep]p3:
4198 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4199 // and let Y be the lookup set produced by argument dependent
4200 // lookup (defined as follows). If X contains
4201 //
4202 // -- a declaration of a class member, or
4203 //
4204 // -- a block-scope function declaration that is not a
4205 // using-declaration (FIXME: check for using declaration), or
4206 //
4207 // -- a declaration that is neither a function or a function
4208 // template
4209 //
4210 // then Y is empty.
4211 if (!Callee) {
4212 // Nothing to do.
4213 } else if (OverloadedFunctionDecl *Ovl
4214 = dyn_cast<OverloadedFunctionDecl>(Callee)) {
4215 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4216 FuncEnd = Ovl->function_end();
4217 Func != FuncEnd; ++Func)
4218 AddOverloadedCallCandidate(*this, *Func, ArgumentDependentLookup,
4219 HasExplicitTemplateArgs,
4220 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4221 Args, NumArgs, CandidateSet,
4222 PartialOverloading);
4223 } else if (isa<FunctionDecl>(Callee) || isa<FunctionTemplateDecl>(Callee))
4224 AddOverloadedCallCandidate(*this,
4225 AnyFunctionDecl::getFromNamedDecl(Callee),
4226 ArgumentDependentLookup,
4227 HasExplicitTemplateArgs,
4228 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4229 Args, NumArgs, CandidateSet,
4230 PartialOverloading);
4231 // FIXME: assert isa<FunctionDecl> || isa<FunctionTemplateDecl> rather than
4232 // checking dynamically.
4233
4234 if (Callee)
4235 UnqualifiedName = Callee->getDeclName();
4236
4237 if (ArgumentDependentLookup)
4238 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
4239 HasExplicitTemplateArgs,
4240 ExplicitTemplateArgs,
4241 NumExplicitTemplateArgs,
4242 CandidateSet,
4243 PartialOverloading);
4244}
4245
Douglas Gregorf6b89692008-11-26 05:54:23 +00004246/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00004247/// (which eventually refers to the declaration Func) and the call
4248/// arguments Args/NumArgs, attempt to resolve the function call down
4249/// to a specific function. If overload resolution succeeds, returns
4250/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00004251/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00004252/// arguments and Fn, and returns NULL.
Douglas Gregorfa047642009-02-04 00:32:51 +00004253FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor17330012009-02-04 15:01:18 +00004254 DeclarationName UnqualifiedName,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004255 bool HasExplicitTemplateArgs,
4256 const TemplateArgument *ExplicitTemplateArgs,
4257 unsigned NumExplicitTemplateArgs,
Douglas Gregor0a396682008-11-26 06:01:48 +00004258 SourceLocation LParenLoc,
4259 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00004260 SourceLocation *CommaLocs,
Douglas Gregorfa047642009-02-04 00:32:51 +00004261 SourceLocation RParenLoc,
Douglas Gregor17330012009-02-04 15:01:18 +00004262 bool &ArgumentDependentLookup) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00004263 OverloadCandidateSet CandidateSet;
Douglas Gregor17330012009-02-04 15:01:18 +00004264
4265 // Add the functions denoted by Callee to the set of candidate
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004266 // functions.
4267 AddOverloadedCallCandidates(Callee, UnqualifiedName, ArgumentDependentLookup,
4268 HasExplicitTemplateArgs, ExplicitTemplateArgs,
4269 NumExplicitTemplateArgs, Args, NumArgs,
4270 CandidateSet);
Douglas Gregorf6b89692008-11-26 05:54:23 +00004271 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004272 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00004273 case OR_Success:
4274 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00004275
4276 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00004277 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00004278 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00004279 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00004280 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4281 break;
4282
4283 case OR_Ambiguous:
4284 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor17330012009-02-04 15:01:18 +00004285 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00004286 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4287 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004288
4289 case OR_Deleted:
4290 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4291 << Best->Function->isDeleted()
4292 << UnqualifiedName
4293 << Fn->getSourceRange();
4294 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4295 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00004296 }
4297
4298 // Overload resolution failed. Destroy all of the subexpressions and
4299 // return NULL.
4300 Fn->Destroy(Context);
4301 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4302 Args[Arg]->Destroy(Context);
4303 return 0;
4304}
4305
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004306/// \brief Create a unary operation that may resolve to an overloaded
4307/// operator.
4308///
4309/// \param OpLoc The location of the operator itself (e.g., '*').
4310///
4311/// \param OpcIn The UnaryOperator::Opcode that describes this
4312/// operator.
4313///
4314/// \param Functions The set of non-member functions that will be
4315/// considered by overload resolution. The caller needs to build this
4316/// set based on the context using, e.g.,
4317/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4318/// set should not contain any member functions; those will be added
4319/// by CreateOverloadedUnaryOp().
4320///
4321/// \param input The input argument.
4322Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4323 unsigned OpcIn,
4324 FunctionSet &Functions,
Mike Stump1eb44332009-09-09 15:08:12 +00004325 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004326 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4327 Expr *Input = (Expr *)input.get();
4328
4329 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4330 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4331 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4332
4333 Expr *Args[2] = { Input, 0 };
4334 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004335
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004336 // For post-increment and post-decrement, add the implicit '0' as
4337 // the second argument, so that we know this is a post-increment or
4338 // post-decrement.
4339 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4340 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00004341 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004342 SourceLocation());
4343 NumArgs = 2;
4344 }
4345
4346 if (Input->isTypeDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004347 OverloadedFunctionDecl *Overloads
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004348 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump1eb44332009-09-09 15:08:12 +00004349 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004350 FuncEnd = Functions.end();
4351 Func != FuncEnd; ++Func)
4352 Overloads->addOverload(*Func);
4353
4354 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4355 OpLoc, false, false);
Mike Stump1eb44332009-09-09 15:08:12 +00004356
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004357 input.release();
4358 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4359 &Args[0], NumArgs,
4360 Context.DependentTy,
4361 OpLoc));
4362 }
4363
4364 // Build an empty overload set.
4365 OverloadCandidateSet CandidateSet;
4366
4367 // Add the candidates from the given function set.
4368 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4369
4370 // Add operator candidates that are member functions.
4371 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4372
4373 // Add builtin operator candidates.
4374 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4375
4376 // Perform overload resolution.
4377 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004378 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004379 case OR_Success: {
4380 // We found a built-in operator or an overloaded operator.
4381 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00004382
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004383 if (FnDecl) {
4384 // We matched an overloaded operator. Build a call to that
4385 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00004386
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004387 // Convert the arguments.
4388 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4389 if (PerformObjectArgumentInitialization(Input, Method))
4390 return ExprError();
4391 } else {
4392 // Convert the arguments.
4393 if (PerformCopyInitialization(Input,
4394 FnDecl->getParamDecl(0)->getType(),
4395 "passing"))
4396 return ExprError();
4397 }
4398
4399 // Determine the result type
4400 QualType ResultTy
John McCall183700f2009-09-21 23:43:11 +00004401 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004402 ResultTy = ResultTy.getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00004403
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004404 // Build the actual expression node.
4405 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4406 SourceLocation());
4407 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004408
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004409 input.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004410
4411 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlsson2d46eb22009-08-16 04:11:06 +00004412 &Input, 1, ResultTy, OpLoc);
4413 return MaybeBindToTemporary(CE);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004414 } else {
4415 // We matched a built-in operator. Convert the arguments, then
4416 // break out so that we will build the appropriate built-in
4417 // operator node.
4418 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4419 Best->Conversions[0], "passing"))
4420 return ExprError();
4421
4422 break;
4423 }
4424 }
4425
4426 case OR_No_Viable_Function:
4427 // No viable function; fall through to handling this as a
4428 // built-in operator, which will produce an error message for us.
4429 break;
4430
4431 case OR_Ambiguous:
4432 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4433 << UnaryOperator::getOpcodeStr(Opc)
4434 << Input->getSourceRange();
4435 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4436 return ExprError();
4437
4438 case OR_Deleted:
4439 Diag(OpLoc, diag::err_ovl_deleted_oper)
4440 << Best->Function->isDeleted()
4441 << UnaryOperator::getOpcodeStr(Opc)
4442 << Input->getSourceRange();
4443 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4444 return ExprError();
4445 }
4446
4447 // Either we found no viable overloaded operator or we matched a
4448 // built-in operator. In either case, fall through to trying to
4449 // build a built-in operation.
4450 input.release();
4451 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4452}
4453
Douglas Gregor063daf62009-03-13 18:40:31 +00004454/// \brief Create a binary operation that may resolve to an overloaded
4455/// operator.
4456///
4457/// \param OpLoc The location of the operator itself (e.g., '+').
4458///
4459/// \param OpcIn The BinaryOperator::Opcode that describes this
4460/// operator.
4461///
4462/// \param Functions The set of non-member functions that will be
4463/// considered by overload resolution. The caller needs to build this
4464/// set based on the context using, e.g.,
4465/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4466/// set should not contain any member functions; those will be added
4467/// by CreateOverloadedBinOp().
4468///
4469/// \param LHS Left-hand argument.
4470/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00004471Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00004472Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004473 unsigned OpcIn,
Douglas Gregor063daf62009-03-13 18:40:31 +00004474 FunctionSet &Functions,
4475 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00004476 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004477 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00004478
4479 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4480 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4481 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4482
4483 // If either side is type-dependent, create an appropriate dependent
4484 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004485 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor063daf62009-03-13 18:40:31 +00004486 // .* cannot be overloaded.
4487 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004488 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
Douglas Gregor063daf62009-03-13 18:40:31 +00004489 Context.DependentTy, OpLoc));
4490
Mike Stump1eb44332009-09-09 15:08:12 +00004491 OverloadedFunctionDecl *Overloads
Douglas Gregor063daf62009-03-13 18:40:31 +00004492 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump1eb44332009-09-09 15:08:12 +00004493 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004494 FuncEnd = Functions.end();
4495 Func != FuncEnd; ++Func)
4496 Overloads->addOverload(*Func);
4497
4498 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4499 OpLoc, false, false);
Mike Stump1eb44332009-09-09 15:08:12 +00004500
Douglas Gregor063daf62009-03-13 18:40:31 +00004501 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00004502 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00004503 Context.DependentTy,
4504 OpLoc));
4505 }
4506
4507 // If this is the .* operator, which is not overloadable, just
4508 // create a built-in binary operator.
4509 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004510 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00004511
4512 // If this is one of the assignment operators, we only perform
4513 // overload resolution if the left-hand side is a class or
4514 // enumeration type (C++ [expr.ass]p3).
4515 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004516 !Args[0]->getType()->isOverloadableType())
4517 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00004518
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004519 // Build an empty overload set.
4520 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00004521
4522 // Add the candidates from the given function set.
4523 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4524
4525 // Add operator candidates that are member functions.
4526 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4527
4528 // Add builtin operator candidates.
4529 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4530
4531 // Perform overload resolution.
4532 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004533 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004534 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00004535 // We found a built-in operator or an overloaded operator.
4536 FunctionDecl *FnDecl = Best->Function;
4537
4538 if (FnDecl) {
4539 // We matched an overloaded operator. Build a call to that
4540 // operator.
4541
4542 // Convert the arguments.
4543 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004544 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4545 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004546 "passing"))
4547 return ExprError();
4548 } else {
4549 // Convert the arguments.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004550 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004551 "passing") ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004552 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004553 "passing"))
4554 return ExprError();
4555 }
4556
4557 // Determine the result type
4558 QualType ResultTy
John McCall183700f2009-09-21 23:43:11 +00004559 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor063daf62009-03-13 18:40:31 +00004560 ResultTy = ResultTy.getNonReferenceType();
4561
4562 // Build the actual expression node.
4563 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00004564 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00004565 UsualUnaryConversions(FnExpr);
4566
Mike Stump1eb44332009-09-09 15:08:12 +00004567 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlsson2d46eb22009-08-16 04:11:06 +00004568 Args, 2, ResultTy, OpLoc);
4569 return MaybeBindToTemporary(CE);
Douglas Gregor063daf62009-03-13 18:40:31 +00004570 } else {
4571 // We matched a built-in operator. Convert the arguments, then
4572 // break out so that we will build the appropriate built-in
4573 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004574 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor063daf62009-03-13 18:40:31 +00004575 Best->Conversions[0], "passing") ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004576 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor063daf62009-03-13 18:40:31 +00004577 Best->Conversions[1], "passing"))
4578 return ExprError();
4579
4580 break;
4581 }
4582 }
4583
4584 case OR_No_Viable_Function:
Sebastian Redl8593c782009-05-21 11:50:50 +00004585 // For class as left operand for assignment or compound assigment operator
4586 // do not fall through to handling in built-in, but report that no overloaded
4587 // assignment operator found
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004588 if (Args[0]->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00004589 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4590 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004591 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Sebastian Redl8593c782009-05-21 11:50:50 +00004592 return ExprError();
4593 }
Douglas Gregor063daf62009-03-13 18:40:31 +00004594 // No viable function; fall through to handling this as a
4595 // built-in operator, which will produce an error message for us.
4596 break;
4597
4598 case OR_Ambiguous:
4599 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4600 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004601 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor063daf62009-03-13 18:40:31 +00004602 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4603 return ExprError();
4604
4605 case OR_Deleted:
4606 Diag(OpLoc, diag::err_ovl_deleted_oper)
4607 << Best->Function->isDeleted()
4608 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004609 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor063daf62009-03-13 18:40:31 +00004610 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4611 return ExprError();
4612 }
4613
4614 // Either we found no viable overloaded operator or we matched a
4615 // built-in operator. In either case, try to build a built-in
4616 // operation.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004617 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00004618}
4619
Douglas Gregor88a35142008-12-22 05:46:06 +00004620/// BuildCallToMemberFunction - Build a call to a member
4621/// function. MemExpr is the expression that refers to the member
4622/// function (and includes the object parameter), Args/NumArgs are the
4623/// arguments to the function call (not including the object
4624/// parameter). The caller needs to validate that the member
4625/// expression refers to a member function or an overloaded member
4626/// function.
4627Sema::ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00004628Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4629 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00004630 unsigned NumArgs, SourceLocation *CommaLocs,
4631 SourceLocation RParenLoc) {
4632 // Dig out the member expression. This holds both the object
4633 // argument and the member function we're referring to.
4634 MemberExpr *MemExpr = 0;
4635 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4636 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4637 else
4638 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4639 assert(MemExpr && "Building member call without member expression");
4640
4641 // Extract the object argument.
4642 Expr *ObjectArg = MemExpr->getBase();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004643
Douglas Gregor88a35142008-12-22 05:46:06 +00004644 CXXMethodDecl *Method = 0;
Douglas Gregor6b906862009-08-21 00:16:32 +00004645 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4646 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004647 // Add overload candidates
4648 OverloadCandidateSet CandidateSet;
Douglas Gregor6b906862009-08-21 00:16:32 +00004649 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00004650
Douglas Gregordec06662009-08-21 18:42:58 +00004651 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4652 Func != FuncEnd; ++Func) {
4653 if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
Mike Stump1eb44332009-09-09 15:08:12 +00004654 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +00004655 /*SuppressUserConversions=*/false);
4656 else
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00004657 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4658 MemExpr->hasExplicitTemplateArgumentList(),
4659 MemExpr->getTemplateArgs(),
4660 MemExpr->getNumTemplateArgs(),
4661 ObjectArg, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00004662 CandidateSet,
4663 /*SuppressUsedConversions=*/false);
4664 }
Mike Stump1eb44332009-09-09 15:08:12 +00004665
Douglas Gregor88a35142008-12-22 05:46:06 +00004666 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004667 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004668 case OR_Success:
4669 Method = cast<CXXMethodDecl>(Best->Function);
4670 break;
4671
4672 case OR_No_Viable_Function:
Mike Stump1eb44332009-09-09 15:08:12 +00004673 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor88a35142008-12-22 05:46:06 +00004674 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00004675 << DeclName << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00004676 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4677 // FIXME: Leaking incoming expressions!
4678 return true;
4679
4680 case OR_Ambiguous:
Mike Stump1eb44332009-09-09 15:08:12 +00004681 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor88a35142008-12-22 05:46:06 +00004682 diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00004683 << DeclName << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00004684 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4685 // FIXME: Leaking incoming expressions!
4686 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004687
4688 case OR_Deleted:
Mike Stump1eb44332009-09-09 15:08:12 +00004689 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004690 diag::err_ovl_deleted_member_call)
4691 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00004692 << DeclName << MemExprE->getSourceRange();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004693 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4694 // FIXME: Leaking incoming expressions!
4695 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004696 }
4697
4698 FixOverloadedFunctionReference(MemExpr, Method);
4699 } else {
4700 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4701 }
4702
4703 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00004704 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek668bf912009-02-09 20:51:47 +00004705 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00004706 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00004707 Method->getResultType().getNonReferenceType(),
4708 RParenLoc));
4709
4710 // Convert the object argument (for a non-static member function call).
Mike Stump1eb44332009-09-09 15:08:12 +00004711 if (!Method->isStatic() &&
Douglas Gregor88a35142008-12-22 05:46:06 +00004712 PerformObjectArgumentInitialization(ObjectArg, Method))
4713 return true;
4714 MemExpr->setBase(ObjectArg);
4715
4716 // Convert the rest of the arguments
Douglas Gregor72564e72009-02-26 23:50:07 +00004717 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004718 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00004719 RParenLoc))
4720 return true;
4721
Anders Carlssond406bf02009-08-16 01:56:34 +00004722 if (CheckFunctionCall(Method, TheCall.get()))
4723 return true;
Anders Carlsson6f680272009-08-16 03:42:12 +00004724
4725 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor88a35142008-12-22 05:46:06 +00004726}
4727
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004728/// BuildCallToObjectOfClassType - Build a call to an object of class
4729/// type (C++ [over.call.object]), which can end up invoking an
4730/// overloaded function call operator (@c operator()) or performing a
4731/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00004732Sema::ExprResult
4733Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00004734 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004735 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00004736 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004737 SourceLocation RParenLoc) {
4738 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00004739 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004740
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004741 // C++ [over.call.object]p1:
4742 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00004743 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004744 // candidate functions includes at least the function call
4745 // operators of T. The function call operators of T are obtained by
4746 // ordinary lookup of the name operator() in the context of
4747 // (E).operator().
4748 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00004749 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004750 DeclContext::lookup_const_iterator Oper, OperEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004751 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004752 Oper != OperEnd; ++Oper)
Mike Stump1eb44332009-09-09 15:08:12 +00004753 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004754 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004755
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004756 // C++ [over.call.object]p2:
4757 // In addition, for each conversion function declared in T of the
4758 // form
4759 //
4760 // operator conversion-type-id () cv-qualifier;
4761 //
4762 // where cv-qualifier is the same cv-qualification as, or a
4763 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00004764 // denotes the type "pointer to function of (P1,...,Pn) returning
4765 // R", or the type "reference to pointer to function of
4766 // (P1,...,Pn) returning R", or the type "reference to function
4767 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004768 // is also considered as a candidate function. Similarly,
4769 // surrogate call functions are added to the set of candidate
4770 // functions for each conversion function declared in an
4771 // accessible base class provided the function is not hidden
4772 // within T by another intervening declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00004773
Douglas Gregor5842ba92009-08-24 15:23:48 +00004774 if (!RequireCompleteType(SourceLocation(), Object->getType(), 0)) {
4775 // FIXME: Look in base classes for more conversion operators!
Mike Stump1eb44332009-09-09 15:08:12 +00004776 OverloadedFunctionDecl *Conversions
Douglas Gregor5842ba92009-08-24 15:23:48 +00004777 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00004778 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor5842ba92009-08-24 15:23:48 +00004779 Func = Conversions->function_begin(),
4780 FuncEnd = Conversions->function_end();
4781 Func != FuncEnd; ++Func) {
4782 CXXConversionDecl *Conv;
4783 FunctionTemplateDecl *ConvTemplate;
4784 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004785
Douglas Gregor5842ba92009-08-24 15:23:48 +00004786 // Skip over templated conversion functions; they aren't
4787 // surrogates.
4788 if (ConvTemplate)
4789 continue;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004790
Douglas Gregor5842ba92009-08-24 15:23:48 +00004791 // Strip the reference type (if any) and then the pointer type (if
4792 // any) to get down to what might be a function type.
4793 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4794 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4795 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004796
John McCall183700f2009-09-21 23:43:11 +00004797 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
Douglas Gregor5842ba92009-08-24 15:23:48 +00004798 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4799 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004800 }
Mike Stump1eb44332009-09-09 15:08:12 +00004801
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004802 // Perform overload resolution.
4803 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004804 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004805 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004806 // Overload resolution succeeded; we'll build the appropriate call
4807 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004808 break;
4809
4810 case OR_No_Viable_Function:
Mike Stump1eb44332009-09-09 15:08:12 +00004811 Diag(Object->getSourceRange().getBegin(),
Sebastian Redle4c452c2008-11-22 13:44:36 +00004812 diag::err_ovl_no_viable_object_call)
Chris Lattner4330d652009-02-17 07:29:20 +00004813 << Object->getType() << Object->getSourceRange();
Sebastian Redle4c452c2008-11-22 13:44:36 +00004814 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004815 break;
4816
4817 case OR_Ambiguous:
4818 Diag(Object->getSourceRange().getBegin(),
4819 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00004820 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004821 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4822 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004823
4824 case OR_Deleted:
4825 Diag(Object->getSourceRange().getBegin(),
4826 diag::err_ovl_deleted_object_call)
4827 << Best->Function->isDeleted()
4828 << Object->getType() << Object->getSourceRange();
4829 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4830 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004831 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004832
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004833 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004834 // We had an error; delete all of the subexpressions and return
4835 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004836 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004837 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00004838 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004839 return true;
4840 }
4841
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004842 if (Best->Function == 0) {
4843 // Since there is no function declaration, this is one of the
4844 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00004845 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004846 = cast<CXXConversionDecl>(
4847 Best->Conversions[0].UserDefined.ConversionFunction);
4848
4849 // We selected one of the surrogate functions that converts the
4850 // object parameter to a function pointer. Perform the conversion
4851 // on the object argument, then let ActOnCallExpr finish the job.
4852 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl0eb23302009-01-19 00:08:26 +00004853 ImpCastExprToType(Object,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004854 Conv->getConversionType().getNonReferenceType(),
Anders Carlsson3503d042009-07-31 01:23:52 +00004855 CastExpr::CK_Unknown,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004856 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00004857 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4858 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4859 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004860 }
4861
4862 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4863 // that calls this method, using Object for the implicit object
4864 // parameter and passing along the remaining arguments.
4865 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00004866 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004867
4868 unsigned NumArgsInProto = Proto->getNumArgs();
4869 unsigned NumArgsToCheck = NumArgs;
4870
4871 // Build the full argument list for the method call (the
4872 // implicit object parameter is placed at the beginning of the
4873 // list).
4874 Expr **MethodArgs;
4875 if (NumArgs < NumArgsInProto) {
4876 NumArgsToCheck = NumArgsInProto;
4877 MethodArgs = new Expr*[NumArgsInProto + 1];
4878 } else {
4879 MethodArgs = new Expr*[NumArgs + 1];
4880 }
4881 MethodArgs[0] = Object;
4882 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4883 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00004884
4885 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004886 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004887 UsualUnaryConversions(NewFn);
4888
4889 // Once we've built TheCall, all of the expressions are properly
4890 // owned.
4891 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00004892 ExprOwningPtr<CXXOperatorCallExpr>
4893 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00004894 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004895 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004896 delete [] MethodArgs;
4897
Douglas Gregor518fda12009-01-13 05:10:00 +00004898 // We may have default arguments. If so, we need to allocate more
4899 // slots in the call for them.
4900 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00004901 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00004902 else if (NumArgs > NumArgsInProto)
4903 NumArgsToCheck = NumArgsInProto;
4904
Chris Lattner312531a2009-04-12 08:11:20 +00004905 bool IsError = false;
4906
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004907 // Initialize the implicit object parameter.
Chris Lattner312531a2009-04-12 08:11:20 +00004908 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004909 TheCall->setArg(0, Object);
4910
Chris Lattner312531a2009-04-12 08:11:20 +00004911
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004912 // Check the argument types.
4913 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004914 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00004915 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004916 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00004917
Douglas Gregor518fda12009-01-13 05:10:00 +00004918 // Pass the argument.
4919 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner312531a2009-04-12 08:11:20 +00004920 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor518fda12009-01-13 05:10:00 +00004921 } else {
Anders Carlssonf1480ee2009-08-14 18:30:22 +00004922 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregor518fda12009-01-13 05:10:00 +00004923 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004924
4925 TheCall->setArg(i + 1, Arg);
4926 }
4927
4928 // If this is a variadic call, handle args passed through "...".
4929 if (Proto->isVariadic()) {
4930 // Promote the arguments (C99 6.5.2.2p7).
4931 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4932 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00004933 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004934 TheCall->setArg(i + 1, Arg);
4935 }
4936 }
4937
Chris Lattner312531a2009-04-12 08:11:20 +00004938 if (IsError) return true;
4939
Anders Carlssond406bf02009-08-16 01:56:34 +00004940 if (CheckFunctionCall(Method, TheCall.get()))
4941 return true;
4942
Anders Carlssona303f9e2009-08-16 03:53:54 +00004943 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004944}
4945
Douglas Gregor8ba10742008-11-20 16:27:02 +00004946/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00004947/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00004948/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004949Sema::OwningExprResult
4950Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
4951 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00004952 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00004953
Douglas Gregor8ba10742008-11-20 16:27:02 +00004954 // C++ [over.ref]p1:
4955 //
4956 // [...] An expression x->m is interpreted as (x.operator->())->m
4957 // for a class object x of type T if T::operator->() exists and if
4958 // the operator is selected as the best match function by the
4959 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00004960 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4961 OverloadCandidateSet CandidateSet;
Ted Kremenek6217b802009-07-29 21:53:49 +00004962 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004963
Anders Carlssone30572a2009-09-10 23:18:36 +00004964 LookupResult R = LookupQualifiedName(BaseRecord->getDecl(), OpName,
4965 LookupOrdinaryName);
4966
4967 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
4968 Oper != OperEnd; ++Oper)
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004969 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00004970 /*SuppressUserConversions=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00004971
4972 // Perform overload resolution.
4973 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004974 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00004975 case OR_Success:
4976 // Overload resolution succeeded; we'll build the call below.
4977 break;
4978
4979 case OR_No_Viable_Function:
4980 if (CandidateSet.empty())
4981 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004982 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004983 else
4984 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004985 << "operator->" << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004986 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004987 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004988
4989 case OR_Ambiguous:
4990 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00004991 << "->" << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004992 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00004993 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004994
4995 case OR_Deleted:
4996 Diag(OpLoc, diag::err_ovl_deleted_oper)
4997 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00004998 << "->" << Base->getSourceRange();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004999 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005000 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005001 }
5002
5003 // Convert the object parameter.
5004 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00005005 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005006 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00005007
5008 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005009 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005010
5011 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00005012 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5013 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00005014 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00005015 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor8ba10742008-11-20 16:27:02 +00005016 Method->getResultType().getNonReferenceType(),
5017 OpLoc);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005018 return Owned(Base);
Douglas Gregor8ba10742008-11-20 16:27:02 +00005019}
5020
Douglas Gregor904eed32008-11-10 20:40:00 +00005021/// FixOverloadedFunctionReference - E is an expression that refers to
5022/// a C++ overloaded function (possibly with some parentheses and
5023/// perhaps a '&' around it). We have resolved the overloaded function
5024/// to the function declaration Fn, so patch up the expression E to
5025/// refer (possibly indirectly) to Fn.
5026void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
5027 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5028 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5029 E->setType(PE->getSubExpr()->getType());
5030 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00005031 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00005032 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00005033 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5034 if (Method->isStatic()) {
5035 // Do nothing: static member functions aren't any different
5036 // from non-member functions.
Mike Stump1eb44332009-09-09 15:08:12 +00005037 } else if (QualifiedDeclRefExpr *DRE
Douglas Gregorb86b0572009-02-11 01:18:59 +00005038 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
5039 // We have taken the address of a pointer to member
5040 // function. Perform the computation here so that we get the
5041 // appropriate pointer to member type.
5042 DRE->setDecl(Fn);
5043 DRE->setType(Fn->getType());
5044 QualType ClassType
5045 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
Mike Stump1eb44332009-09-09 15:08:12 +00005046 E->setType(Context.getMemberPointerType(Fn->getType(),
Douglas Gregorb86b0572009-02-11 01:18:59 +00005047 ClassType.getTypePtr()));
5048 return;
5049 }
5050 }
Douglas Gregor904eed32008-11-10 20:40:00 +00005051 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregora35284b2009-02-11 00:19:33 +00005052 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor904eed32008-11-10 20:40:00 +00005053 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00005054 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
Mike Stump1eb44332009-09-09 15:08:12 +00005055 isa<FunctionTemplateDecl>(DR->getDecl())) &&
Douglas Gregor83314aa2009-07-08 20:55:45 +00005056 "Expected overloaded function or function template");
Douglas Gregor904eed32008-11-10 20:40:00 +00005057 DR->setDecl(Fn);
5058 E->setType(Fn->getType());
Douglas Gregor88a35142008-12-22 05:46:06 +00005059 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
5060 MemExpr->setMemberDecl(Fn);
5061 E->setType(Fn->getType());
Douglas Gregor904eed32008-11-10 20:40:00 +00005062 } else {
5063 assert(false && "Invalid reference to overloaded function");
5064 }
5065}
5066
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005067} // end namespace clang