blob: 6ea6a145576d249f27c476d474adb3d90512f262 [file] [log] [blame]
Douglas Gregor5251f1b2008-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"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000020#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000022#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000024#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000025#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000026#include <algorithm>
Torok Edwindb714922009-08-24 13:25:12 +000027#include <cstdio>
Douglas Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor5251f1b2008-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 Gregor78ca74d2009-02-12 00:15:05 +000044 ICC_Promotion,
45 ICC_Conversion,
46 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000047 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000052 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000053 ICC_Conversion,
Douglas Gregor5251f1b2008-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 Gregor78ca74d2009-02-12 00:15:05 +000071 ICR_Promotion,
72 ICR_Conversion,
73 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000074 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000079 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000080 ICR_Conversion,
Douglas Gregor5251f1b2008-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 Gregor78ca74d2009-02-12 00:15:05 +000097 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +000098 "Integral conversion",
99 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000100 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 "Floating-integral conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000102 "Complex-real conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000103 "Pointer conversion",
104 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000105 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000106 "Compatible-types conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000107 "Derived-to-base conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000108 };
109 return Name[Kind];
110}
111
Douglas Gregor26bee0b2008-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 Redlf69a94a2009-03-29 22:46:24 +0000121 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000122 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000123}
124
Douglas Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +0000141/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000142/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000143bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-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 Gregor033f56d2008-12-23 00:53:59 +0000152 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor5251f1b2008-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 Gregor5c407d92008-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 Stump11289f42009-09-09 15:08:12 +0000163bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
Douglas Gregor5c407d92008-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 Kremenekc23c7e62009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor5251f1b2008-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 Gregor2fe98832008-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 Gregor5251f1b2008-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 Lattnerf3d3fae2008-11-24 05:29:24 +0000227 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +0000263// FunctionDecl that New cannot be overloaded with.
Douglas Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +0000272// so IsOverload will not be used.
Douglas Gregor5251f1b2008-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
John McCall1f82f242009-11-18 22:49:29 +0000286Sema::IsOverload(FunctionDecl *New, LookupResult &Previous, NamedDecl *&Match) {
287 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
288 I != E; ++I) {
289 NamedDecl *Old = (*I)->getUnderlyingDecl();
290 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(Old)) {
291 if (!IsOverload(New, OldT->getTemplatedDecl())) {
292 Match = Old;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000293 return false;
294 }
John McCall1f82f242009-11-18 22:49:29 +0000295 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(Old)) {
296 if (!IsOverload(New, OldF)) {
297 Match = Old;
298 return false;
299 }
300 } else {
301 // (C++ 13p1):
302 // Only function declarations can be overloaded; object and type
303 // declarations cannot be overloaded.
304 Match = Old;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000305 return false;
John McCall1f82f242009-11-18 22:49:29 +0000306 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000307 }
John McCall1f82f242009-11-18 22:49:29 +0000308
309 return true;
310}
311
312bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
313 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
314 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
315
316 // C++ [temp.fct]p2:
317 // A function template can be overloaded with other function templates
318 // and with normal (non-template) functions.
319 if ((OldTemplate == 0) != (NewTemplate == 0))
320 return true;
321
322 // Is the function New an overload of the function Old?
323 QualType OldQType = Context.getCanonicalType(Old->getType());
324 QualType NewQType = Context.getCanonicalType(New->getType());
325
326 // Compare the signatures (C++ 1.3.10) of the two functions to
327 // determine whether they are overloads. If we find any mismatch
328 // in the signature, they are overloads.
329
330 // If either of these functions is a K&R-style function (no
331 // prototype), then we consider them to have matching signatures.
332 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
333 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
334 return false;
335
336 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
337 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
338
339 // The signature of a function includes the types of its
340 // parameters (C++ 1.3.10), which includes the presence or absence
341 // of the ellipsis; see C++ DR 357).
342 if (OldQType != NewQType &&
343 (OldType->getNumArgs() != NewType->getNumArgs() ||
344 OldType->isVariadic() != NewType->isVariadic() ||
345 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
346 NewType->arg_type_begin())))
347 return true;
348
349 // C++ [temp.over.link]p4:
350 // The signature of a function template consists of its function
351 // signature, its return type and its template parameter list. The names
352 // of the template parameters are significant only for establishing the
353 // relationship between the template parameters and the rest of the
354 // signature.
355 //
356 // We check the return type and template parameter lists for function
357 // templates first; the remaining checks follow.
358 if (NewTemplate &&
359 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
360 OldTemplate->getTemplateParameters(),
361 false, TPL_TemplateMatch) ||
362 OldType->getResultType() != NewType->getResultType()))
363 return true;
364
365 // If the function is a class member, its signature includes the
366 // cv-qualifiers (if any) on the function itself.
367 //
368 // As part of this, also check whether one of the member functions
369 // is static, in which case they are not overloads (C++
370 // 13.1p2). While not part of the definition of the signature,
371 // this check is important to determine whether these functions
372 // can be overloaded.
373 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
374 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
375 if (OldMethod && NewMethod &&
376 !OldMethod->isStatic() && !NewMethod->isStatic() &&
377 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
378 return true;
379
380 // The signatures match; this is not an overload.
381 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000382}
383
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000384/// TryImplicitConversion - Attempt to perform an implicit conversion
385/// from the given expression (Expr) to the given type (ToType). This
386/// function returns an implicit conversion sequence that can be used
387/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000388///
389/// void f(float f);
390/// void g(int i) { f(i); }
391///
392/// this routine would produce an implicit conversion sequence to
393/// describe the initialization of f from i, which will be a standard
394/// conversion sequence containing an lvalue-to-rvalue conversion (C++
395/// 4.1) followed by a floating-integral conversion (C++ 4.9).
396//
397/// Note that this routine only determines how the conversion can be
398/// performed; it does not actually perform the conversion. As such,
399/// it will not produce any diagnostics if no conversion is available,
400/// but will instead return an implicit conversion sequence of kind
401/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000402///
403/// If @p SuppressUserConversions, then user-defined conversions are
404/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000405/// If @p AllowExplicit, then explicit user-defined conversions are
406/// permitted.
Sebastian Redl42e92c42009-04-12 17:16:29 +0000407/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
408/// no matter its actual lvalueness.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000409/// If @p UserCast, the implicit conversion is being done for a user-specified
410/// cast.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000411ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000412Sema::TryImplicitConversion(Expr* From, QualType ToType,
413 bool SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +0000414 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000415 bool InOverloadResolution,
416 bool UserCast) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000417 ImplicitConversionSequence ICS;
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000418 OverloadCandidateSet Conversions;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000419 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson228eea32009-08-28 15:33:32 +0000420 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000421 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000422 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000423 (UserDefResult = IsUserDefinedConversion(From, ToType,
424 ICS.UserDefined,
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000425 Conversions,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000426 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000427 ForceRValue, UserCast)) == OR_Success) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000428 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor05379422008-11-03 17:51:48 +0000429 // C++ [over.ics.user]p4:
430 // A conversion of an expression of class type to the same class
431 // type is given Exact Match rank, and a conversion of an
432 // expression of class type to a base class of that type is
433 // given Conversion rank, in spite of the fact that a copy
434 // constructor (i.e., a user-defined conversion function) is
435 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000436 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000437 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000438 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000439 = Context.getCanonicalType(From->getType().getUnqualifiedType());
440 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
441 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000442 // Turn this into a "standard" conversion sequence, so that it
443 // gets ranked with standard conversion sequences.
Douglas Gregor05379422008-11-03 17:51:48 +0000444 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
445 ICS.Standard.setAsIdentityConversion();
446 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
447 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000448 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000449 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000450 ICS.Standard.Second = ICK_Derived_To_Base;
451 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000452 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000453
454 // C++ [over.best.ics]p4:
455 // However, when considering the argument of a user-defined
456 // conversion function that is a candidate by 13.3.1.3 when
457 // invoked for the copying of the temporary in the second step
458 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
459 // 13.3.1.6 in all cases, only standard conversion sequences and
460 // ellipsis conversion sequences are allowed.
461 if (SuppressUserConversions &&
462 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
463 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000464 } else {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000465 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000466 if (UserDefResult == OR_Ambiguous) {
467 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
468 Cand != Conversions.end(); ++Cand)
Fariborz Jahanian574de2c2009-10-12 17:51:19 +0000469 if (Cand->Viable)
470 ICS.ConversionFunctionSet.push_back(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000471 }
472 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000473
474 return ICS;
475}
476
477/// IsStandardConversion - Determines whether there is a standard
478/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
479/// expression From to the type ToType. Standard conversion sequences
480/// only consider non-class types; for conversions that involve class
481/// types, use TryImplicitConversion. If a conversion exists, SCS will
482/// contain the standard conversion sequence required to perform this
483/// conversion and this routine will return true. Otherwise, this
484/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000485bool
486Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000487 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000488 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000489 QualType FromType = From->getType();
490
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000491 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000492 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000493 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000494 SCS.IncompatibleObjC = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000495 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000496 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000497
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000498 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000499 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000500 if (FromType->isRecordType() || ToType->isRecordType()) {
501 if (getLangOptions().CPlusPlus)
502 return false;
503
Mike Stump11289f42009-09-09 15:08:12 +0000504 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000505 }
506
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000507 // The first conversion can be an lvalue-to-rvalue conversion,
508 // array-to-pointer conversion, or function-to-pointer conversion
509 // (C++ 4p1).
510
Mike Stump11289f42009-09-09 15:08:12 +0000511 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000512 // An lvalue (3.10) of a non-function, non-array type T can be
513 // converted to an rvalue.
514 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000515 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000516 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000517 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000518 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000519
520 // If T is a non-class type, the type of the rvalue is the
521 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000522 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
523 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000524 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000525 } else if (FromType->isArrayType()) {
526 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000527 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000528
529 // An lvalue or rvalue of type "array of N T" or "array of unknown
530 // bound of T" can be converted to an rvalue of type "pointer to
531 // T" (C++ 4.2p1).
532 FromType = Context.getArrayDecayedType(FromType);
533
534 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
535 // This conversion is deprecated. (C++ D.4).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000536 SCS.Deprecated = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000537
538 // For the purpose of ranking in overload resolution
539 // (13.3.3.1.1), this conversion is considered an
540 // array-to-pointer conversion followed by a qualification
541 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000542 SCS.Second = ICK_Identity;
543 SCS.Third = ICK_Qualification;
544 SCS.ToTypePtr = ToType.getAsOpaquePtr();
545 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000546 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000547 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
548 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000549 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000550
551 // An lvalue of function type T can be converted to an rvalue of
552 // type "pointer to T." The result is a pointer to the
553 // function. (C++ 4.3p1).
554 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000555 } else if (FunctionDecl *Fn
Douglas Gregorcd695e52008-11-10 20:40:00 +0000556 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000557 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000558 SCS.First = ICK_Function_To_Pointer;
559
560 // We were able to resolve the address of the overloaded function,
561 // so we can convert to the type of that function.
562 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000563 if (ToType->isLValueReferenceType())
564 FromType = Context.getLValueReferenceType(FromType);
565 else if (ToType->isRValueReferenceType())
566 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000567 else if (ToType->isMemberPointerType()) {
568 // Resolve address only succeeds if both sides are member pointers,
569 // but it doesn't have to be the same class. See DR 247.
570 // Note that this means that the type of &Derived::fn can be
571 // Ret (Base::*)(Args) if the fn overload actually found is from the
572 // base class, even if it was brought into the derived class via a
573 // using declaration. The standard isn't clear on this issue at all.
574 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
575 FromType = Context.getMemberPointerType(FromType,
576 Context.getTypeDeclType(M->getParent()).getTypePtr());
577 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000578 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000579 } else {
580 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000581 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000582 }
583
584 // The second conversion can be an integral promotion, floating
585 // point promotion, integral conversion, floating point conversion,
586 // floating-integral conversion, pointer conversion,
587 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000588 // For overloading in C, this can also be a "compatible-type"
589 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000590 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000591 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000592 // The unqualified versions of the types are the same: there's no
593 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000594 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000595 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000596 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000597 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000598 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000599 } else if (IsFloatingPointPromotion(FromType, ToType)) {
600 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000601 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000602 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000603 } else if (IsComplexPromotion(FromType, ToType)) {
604 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000605 SCS.Second = ICK_Complex_Promotion;
606 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000607 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000608 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000609 // Integral conversions (C++ 4.7).
610 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000611 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000612 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000613 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
614 // Floating point conversions (C++ 4.8).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000615 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000616 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000617 } else if (FromType->isComplexType() && ToType->isComplexType()) {
618 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000619 SCS.Second = ICK_Complex_Conversion;
620 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000621 } else if ((FromType->isFloatingType() &&
622 ToType->isIntegralType() && (!ToType->isBooleanType() &&
623 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000624 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000625 ToType->isFloatingType())) {
626 // Floating-integral conversions (C++ 4.9).
627 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000628 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000629 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000630 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
631 (ToType->isComplexType() && FromType->isArithmeticType())) {
632 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000633 SCS.Second = ICK_Complex_Real;
634 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000635 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
636 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000637 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000638 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000639 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000640 } else if (IsMemberPointerConversion(From, FromType, ToType,
641 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000642 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000643 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000644 } else if (ToType->isBooleanType() &&
645 (FromType->isArithmeticType() ||
646 FromType->isEnumeralType() ||
647 FromType->isPointerType() ||
648 FromType->isBlockPointerType() ||
649 FromType->isMemberPointerType() ||
650 FromType->isNullPtrType())) {
651 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000652 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000653 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000654 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000655 Context.typesAreCompatible(ToType, FromType)) {
656 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000657 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000658 } else {
659 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000660 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000661 }
662
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000663 QualType CanonFrom;
664 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000665 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000666 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000667 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000668 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000669 CanonFrom = Context.getCanonicalType(FromType);
670 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000671 } else {
672 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000673 SCS.Third = ICK_Identity;
674
Mike Stump11289f42009-09-09 15:08:12 +0000675 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000676 // [...] Any difference in top-level cv-qualification is
677 // subsumed by the initialization itself and does not constitute
678 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000679 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000680 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000681 if (CanonFrom.getLocalUnqualifiedType()
682 == CanonTo.getLocalUnqualifiedType() &&
683 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000684 FromType = ToType;
685 CanonFrom = CanonTo;
686 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000687 }
688
689 // If we have not converted the argument type to the parameter type,
690 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000691 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000692 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000693
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000694 SCS.ToTypePtr = FromType.getAsOpaquePtr();
695 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000696}
697
698/// IsIntegralPromotion - Determines whether the conversion from the
699/// expression From (whose potentially-adjusted type is FromType) to
700/// ToType is an integral promotion (C++ 4.5). If so, returns true and
701/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000702bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000703 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000704 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000705 if (!To) {
706 return false;
707 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000708
709 // An rvalue of type char, signed char, unsigned char, short int, or
710 // unsigned short int can be converted to an rvalue of type int if
711 // int can represent all the values of the source type; otherwise,
712 // the source rvalue can be converted to an rvalue of type unsigned
713 // int (C++ 4.5p1).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000714 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000715 if (// We can promote any signed, promotable integer type to an int
716 (FromType->isSignedIntegerType() ||
717 // We can promote any unsigned integer type whose size is
718 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000719 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000720 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000721 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000722 }
723
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000724 return To->getKind() == BuiltinType::UInt;
725 }
726
727 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
728 // can be converted to an rvalue of the first of the following types
729 // that can represent all the values of its underlying type: int,
730 // unsigned int, long, or unsigned long (C++ 4.5p2).
731 if ((FromType->isEnumeralType() || FromType->isWideCharType())
732 && ToType->isIntegerType()) {
733 // Determine whether the type we're converting from is signed or
734 // unsigned.
735 bool FromIsSigned;
736 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall9dd450b2009-09-21 23:43:11 +0000737 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000738 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
739 FromIsSigned = UnderlyingType->isSignedIntegerType();
740 } else {
741 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
742 FromIsSigned = true;
743 }
744
745 // The types we'll try to promote to, in the appropriate
746 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000747 QualType PromoteTypes[6] = {
748 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000749 Context.LongTy, Context.UnsignedLongTy ,
750 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000751 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000752 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000753 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
754 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000755 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000756 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
757 // We found the type that we can promote to. If this is the
758 // type we wanted, we have a promotion. Otherwise, no
759 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000760 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000761 }
762 }
763 }
764
765 // An rvalue for an integral bit-field (9.6) can be converted to an
766 // rvalue of type int if int can represent all the values of the
767 // bit-field; otherwise, it can be converted to unsigned int if
768 // unsigned int can represent all the values of the bit-field. If
769 // the bit-field is larger yet, no integral promotion applies to
770 // it. If the bit-field has an enumerated type, it is treated as any
771 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000772 // FIXME: We should delay checking of bit-fields until we actually perform the
773 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000774 using llvm::APSInt;
775 if (From)
776 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000777 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000778 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
779 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
780 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
781 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000782
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000783 // Are we promoting to an int from a bitfield that fits in an int?
784 if (BitWidth < ToSize ||
785 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
786 return To->getKind() == BuiltinType::Int;
787 }
Mike Stump11289f42009-09-09 15:08:12 +0000788
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000789 // Are we promoting to an unsigned int from an unsigned bitfield
790 // that fits into an unsigned int?
791 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
792 return To->getKind() == BuiltinType::UInt;
793 }
Mike Stump11289f42009-09-09 15:08:12 +0000794
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000795 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000796 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000797 }
Mike Stump11289f42009-09-09 15:08:12 +0000798
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000799 // An rvalue of type bool can be converted to an rvalue of type int,
800 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000801 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000802 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000803 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000804
805 return false;
806}
807
808/// IsFloatingPointPromotion - Determines whether the conversion from
809/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
810/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000811bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000812 /// An rvalue of type float can be converted to an rvalue of type
813 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000814 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
815 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000816 if (FromBuiltin->getKind() == BuiltinType::Float &&
817 ToBuiltin->getKind() == BuiltinType::Double)
818 return true;
819
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000820 // C99 6.3.1.5p1:
821 // When a float is promoted to double or long double, or a
822 // double is promoted to long double [...].
823 if (!getLangOptions().CPlusPlus &&
824 (FromBuiltin->getKind() == BuiltinType::Float ||
825 FromBuiltin->getKind() == BuiltinType::Double) &&
826 (ToBuiltin->getKind() == BuiltinType::LongDouble))
827 return true;
828 }
829
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000830 return false;
831}
832
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000833/// \brief Determine if a conversion is a complex promotion.
834///
835/// A complex promotion is defined as a complex -> complex conversion
836/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000837/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000838bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000839 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000840 if (!FromComplex)
841 return false;
842
John McCall9dd450b2009-09-21 23:43:11 +0000843 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000844 if (!ToComplex)
845 return false;
846
847 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000848 ToComplex->getElementType()) ||
849 IsIntegralPromotion(0, FromComplex->getElementType(),
850 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000851}
852
Douglas Gregor237f96c2008-11-26 23:31:11 +0000853/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
854/// the pointer type FromPtr to a pointer to type ToPointee, with the
855/// same type qualifiers as FromPtr has on its pointee type. ToType,
856/// if non-empty, will be a pointer to ToType that may or may not have
857/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000858static QualType
859BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000860 QualType ToPointee, QualType ToType,
861 ASTContext &Context) {
862 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
863 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000864 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000865
866 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000867 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000868 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000869 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000870 return ToType;
871
872 // Build a pointer to ToPointee. It has the right qualifiers
873 // already.
874 return Context.getPointerType(ToPointee);
875 }
876
877 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000878 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000879 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
880 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000881}
882
Mike Stump11289f42009-09-09 15:08:12 +0000883static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000884 bool InOverloadResolution,
885 ASTContext &Context) {
886 // Handle value-dependent integral null pointer constants correctly.
887 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
888 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
889 Expr->getType()->isIntegralType())
890 return !InOverloadResolution;
891
Douglas Gregor56751b52009-09-25 04:25:58 +0000892 return Expr->isNullPointerConstant(Context,
893 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
894 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +0000895}
Mike Stump11289f42009-09-09 15:08:12 +0000896
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000897/// IsPointerConversion - Determines whether the conversion of the
898/// expression From, which has the (possibly adjusted) type FromType,
899/// can be converted to the type ToType via a pointer conversion (C++
900/// 4.10). If so, returns true and places the converted type (that
901/// might differ from ToType in its cv-qualifiers at some level) into
902/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000903///
Douglas Gregora29dc052008-11-27 01:19:21 +0000904/// This routine also supports conversions to and from block pointers
905/// and conversions with Objective-C's 'id', 'id<protocols...>', and
906/// pointers to interfaces. FIXME: Once we've determined the
907/// appropriate overloading rules for Objective-C, we may want to
908/// split the Objective-C checks into a different routine; however,
909/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000910/// conversions, so for now they live here. IncompatibleObjC will be
911/// set if the conversion is an allowed Objective-C conversion that
912/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000913bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000914 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000915 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +0000916 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +0000917 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +0000918 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
919 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000920
Mike Stump11289f42009-09-09 15:08:12 +0000921 // Conversion from a null pointer constant to any Objective-C pointer type.
922 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000923 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +0000924 ConvertedType = ToType;
925 return true;
926 }
927
Douglas Gregor231d1c62008-11-27 00:15:41 +0000928 // Blocks: Block pointers can be converted to void*.
929 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000930 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000931 ConvertedType = ToType;
932 return true;
933 }
934 // Blocks: A null pointer constant can be converted to a block
935 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +0000936 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000937 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000938 ConvertedType = ToType;
939 return true;
940 }
941
Sebastian Redl576fd422009-05-10 18:38:11 +0000942 // If the left-hand-side is nullptr_t, the right side can be a null
943 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000944 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000945 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +0000946 ConvertedType = ToType;
947 return true;
948 }
949
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000950 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000951 if (!ToTypePtr)
952 return false;
953
954 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +0000955 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000956 ConvertedType = ToType;
957 return true;
958 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000959
Douglas Gregor237f96c2008-11-26 23:31:11 +0000960 // Beyond this point, both types need to be pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000961 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +0000962 if (!FromTypePtr)
963 return false;
964
965 QualType FromPointeeType = FromTypePtr->getPointeeType();
966 QualType ToPointeeType = ToTypePtr->getPointeeType();
967
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000968 // An rvalue of type "pointer to cv T," where T is an object type,
969 // can be converted to an rvalue of type "pointer to cv void" (C++
970 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +0000971 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000972 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +0000973 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000974 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000975 return true;
976 }
977
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000978 // When we're overloading in C, we allow a special kind of pointer
979 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +0000980 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000981 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000982 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000983 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +0000984 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000985 return true;
986 }
987
Douglas Gregor5c407d92008-10-23 00:40:37 +0000988 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +0000989 //
Douglas Gregor5c407d92008-10-23 00:40:37 +0000990 // An rvalue of type "pointer to cv D," where D is a class type,
991 // can be converted to an rvalue of type "pointer to cv B," where
992 // B is a base class (clause 10) of D. If B is an inaccessible
993 // (clause 11) or ambiguous (10.2) base class of D, a program that
994 // necessitates this conversion is ill-formed. The result of the
995 // conversion is a pointer to the base class sub-object of the
996 // derived class object. The null pointer value is converted to
997 // the null pointer value of the destination type.
998 //
Douglas Gregor39c16d42008-10-24 04:54:22 +0000999 // Note that we do not check for ambiguity or inaccessibility
1000 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001001 if (getLangOptions().CPlusPlus &&
1002 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001003 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001004 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001005 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001006 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001007 ToType, Context);
1008 return true;
1009 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001010
Douglas Gregora119f102008-12-19 19:13:09 +00001011 return false;
1012}
1013
1014/// isObjCPointerConversion - Determines whether this is an
1015/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1016/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001017bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001018 QualType& ConvertedType,
1019 bool &IncompatibleObjC) {
1020 if (!getLangOptions().ObjC1)
1021 return false;
1022
Steve Naroff7cae42b2009-07-10 23:34:53 +00001023 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001024 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001025 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001026 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001027
Steve Naroff7cae42b2009-07-10 23:34:53 +00001028 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001029 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001030 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001031 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001032 ConvertedType = ToType;
1033 return true;
1034 }
1035 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001036 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001037 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001038 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001039 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001040 ConvertedType = ToType;
1041 return true;
1042 }
1043 // Objective C++: We're able to convert from a pointer to an
1044 // interface to a pointer to a different interface.
1045 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1046 ConvertedType = ToType;
1047 return true;
1048 }
1049
1050 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1051 // Okay: this is some kind of implicit downcast of Objective-C
1052 // interfaces, which is permitted. However, we're going to
1053 // complain about it.
1054 IncompatibleObjC = true;
1055 ConvertedType = FromType;
1056 return true;
1057 }
Mike Stump11289f42009-09-09 15:08:12 +00001058 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001059 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001060 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001061 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001062 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001063 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001064 ToPointeeType = ToBlockPtr->getPointeeType();
1065 else
Douglas Gregora119f102008-12-19 19:13:09 +00001066 return false;
1067
Douglas Gregor033f56d2008-12-23 00:53:59 +00001068 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001069 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001070 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001071 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001072 FromPointeeType = FromBlockPtr->getPointeeType();
1073 else
Douglas Gregora119f102008-12-19 19:13:09 +00001074 return false;
1075
Douglas Gregora119f102008-12-19 19:13:09 +00001076 // If we have pointers to pointers, recursively check whether this
1077 // is an Objective-C conversion.
1078 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1079 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1080 IncompatibleObjC)) {
1081 // We always complain about this conversion.
1082 IncompatibleObjC = true;
1083 ConvertedType = ToType;
1084 return true;
1085 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001086 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001087 // differences in the argument and result types are in Objective-C
1088 // pointer conversions. If so, we permit the conversion (but
1089 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001090 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001091 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001092 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001093 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001094 if (FromFunctionType && ToFunctionType) {
1095 // If the function types are exactly the same, this isn't an
1096 // Objective-C pointer conversion.
1097 if (Context.getCanonicalType(FromPointeeType)
1098 == Context.getCanonicalType(ToPointeeType))
1099 return false;
1100
1101 // Perform the quick checks that will tell us whether these
1102 // function types are obviously different.
1103 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1104 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1105 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1106 return false;
1107
1108 bool HasObjCConversion = false;
1109 if (Context.getCanonicalType(FromFunctionType->getResultType())
1110 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1111 // Okay, the types match exactly. Nothing to do.
1112 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1113 ToFunctionType->getResultType(),
1114 ConvertedType, IncompatibleObjC)) {
1115 // Okay, we have an Objective-C pointer conversion.
1116 HasObjCConversion = true;
1117 } else {
1118 // Function types are too different. Abort.
1119 return false;
1120 }
Mike Stump11289f42009-09-09 15:08:12 +00001121
Douglas Gregora119f102008-12-19 19:13:09 +00001122 // Check argument types.
1123 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1124 ArgIdx != NumArgs; ++ArgIdx) {
1125 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1126 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1127 if (Context.getCanonicalType(FromArgType)
1128 == Context.getCanonicalType(ToArgType)) {
1129 // Okay, the types match exactly. Nothing to do.
1130 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1131 ConvertedType, IncompatibleObjC)) {
1132 // Okay, we have an Objective-C pointer conversion.
1133 HasObjCConversion = true;
1134 } else {
1135 // Argument types are too different. Abort.
1136 return false;
1137 }
1138 }
1139
1140 if (HasObjCConversion) {
1141 // We had an Objective-C conversion. Allow this pointer
1142 // conversion, but complain about it.
1143 ConvertedType = ToType;
1144 IncompatibleObjC = true;
1145 return true;
1146 }
1147 }
1148
Sebastian Redl72b597d2009-01-25 19:43:20 +00001149 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001150}
1151
Douglas Gregor39c16d42008-10-24 04:54:22 +00001152/// CheckPointerConversion - Check the pointer conversion from the
1153/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001154/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001155/// conversions for which IsPointerConversion has already returned
1156/// true. It returns true and produces a diagnostic if there was an
1157/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001158bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001159 CastExpr::CastKind &Kind,
1160 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001161 QualType FromType = From->getType();
1162
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001163 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1164 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001165 QualType FromPointeeType = FromPtrType->getPointeeType(),
1166 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001167
Douglas Gregor39c16d42008-10-24 04:54:22 +00001168 if (FromPointeeType->isRecordType() &&
1169 ToPointeeType->isRecordType()) {
1170 // We must have a derived-to-base conversion. Check an
1171 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001172 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1173 From->getExprLoc(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001174 From->getSourceRange(),
1175 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001176 return true;
1177
1178 // The conversion was successful.
1179 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001180 }
1181 }
Mike Stump11289f42009-09-09 15:08:12 +00001182 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001183 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001184 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001185 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001186 // Objective-C++ conversions are always okay.
1187 // FIXME: We should have a different class of conversions for the
1188 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001189 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001190 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001191
Steve Naroff7cae42b2009-07-10 23:34:53 +00001192 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001193 return false;
1194}
1195
Sebastian Redl72b597d2009-01-25 19:43:20 +00001196/// IsMemberPointerConversion - Determines whether the conversion of the
1197/// expression From, which has the (possibly adjusted) type FromType, can be
1198/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1199/// If so, returns true and places the converted type (that might differ from
1200/// ToType in its cv-qualifiers at some level) into ConvertedType.
1201bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001202 QualType ToType,
1203 bool InOverloadResolution,
1204 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001205 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001206 if (!ToTypePtr)
1207 return false;
1208
1209 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001210 if (From->isNullPointerConstant(Context,
1211 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1212 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001213 ConvertedType = ToType;
1214 return true;
1215 }
1216
1217 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001218 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001219 if (!FromTypePtr)
1220 return false;
1221
1222 // A pointer to member of B can be converted to a pointer to member of D,
1223 // where D is derived from B (C++ 4.11p2).
1224 QualType FromClass(FromTypePtr->getClass(), 0);
1225 QualType ToClass(ToTypePtr->getClass(), 0);
1226 // FIXME: What happens when these are dependent? Is this function even called?
1227
1228 if (IsDerivedFrom(ToClass, FromClass)) {
1229 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1230 ToClass.getTypePtr());
1231 return true;
1232 }
1233
1234 return false;
1235}
1236
1237/// CheckMemberPointerConversion - Check the member pointer conversion from the
1238/// expression From to the type ToType. This routine checks for ambiguous or
1239/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1240/// for which IsMemberPointerConversion has already returned true. It returns
1241/// true and produces a diagnostic if there was an error, or returns false
1242/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001243bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001244 CastExpr::CastKind &Kind,
1245 bool IgnoreBaseAccess) {
1246 (void)IgnoreBaseAccess;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001247 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001248 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001249 if (!FromPtrType) {
1250 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001251 assert(From->isNullPointerConstant(Context,
1252 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001253 "Expr must be null pointer constant!");
1254 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001255 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001256 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001257
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001258 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001259 assert(ToPtrType && "No member pointer cast has a target type "
1260 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001261
Sebastian Redled8f2002009-01-28 18:33:18 +00001262 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1263 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001264
Sebastian Redled8f2002009-01-28 18:33:18 +00001265 // FIXME: What about dependent types?
1266 assert(FromClass->isRecordType() && "Pointer into non-class.");
1267 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001268
Douglas Gregor36d1b142009-10-06 17:59:45 +00001269 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1270 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001271 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1272 assert(DerivationOkay &&
1273 "Should not have been called if derivation isn't OK.");
1274 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001275
Sebastian Redled8f2002009-01-28 18:33:18 +00001276 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1277 getUnqualifiedType())) {
1278 // Derivation is ambiguous. Redo the check to find the exact paths.
1279 Paths.clear();
1280 Paths.setRecordingPaths(true);
1281 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1282 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1283 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001284
Sebastian Redled8f2002009-01-28 18:33:18 +00001285 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1286 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1287 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1288 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001289 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001290
Douglas Gregor89ee6822009-02-28 01:32:25 +00001291 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001292 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1293 << FromClass << ToClass << QualType(VBase, 0)
1294 << From->getSourceRange();
1295 return true;
1296 }
1297
Anders Carlssond7923c62009-08-22 23:33:40 +00001298 // Must be a base to derived member conversion.
1299 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001300 return false;
1301}
1302
Douglas Gregor9a657932008-10-21 23:43:52 +00001303/// IsQualificationConversion - Determines whether the conversion from
1304/// an rvalue of type FromType to ToType is a qualification conversion
1305/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001306bool
1307Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001308 FromType = Context.getCanonicalType(FromType);
1309 ToType = Context.getCanonicalType(ToType);
1310
1311 // If FromType and ToType are the same type, this is not a
1312 // qualification conversion.
1313 if (FromType == ToType)
1314 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001315
Douglas Gregor9a657932008-10-21 23:43:52 +00001316 // (C++ 4.4p4):
1317 // A conversion can add cv-qualifiers at levels other than the first
1318 // in multi-level pointers, subject to the following rules: [...]
1319 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001320 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001321 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001322 // Within each iteration of the loop, we check the qualifiers to
1323 // determine if this still looks like a qualification
1324 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001325 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001326 // until there are no more pointers or pointers-to-members left to
1327 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001328 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001329
1330 // -- for every j > 0, if const is in cv 1,j then const is in cv
1331 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001332 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001333 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001334
Douglas Gregor9a657932008-10-21 23:43:52 +00001335 // -- if the cv 1,j and cv 2,j are different, then const is in
1336 // every cv for 0 < k < j.
1337 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001338 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001339 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001340
Douglas Gregor9a657932008-10-21 23:43:52 +00001341 // Keep track of whether all prior cv-qualifiers in the "to" type
1342 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001343 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001344 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001345 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001346
1347 // We are left with FromType and ToType being the pointee types
1348 // after unwrapping the original FromType and ToType the same number
1349 // of types. If we unwrapped any pointers, and if FromType and
1350 // ToType have the same unqualified type (since we checked
1351 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001352 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001353}
1354
Douglas Gregor576e98c2009-01-30 23:27:23 +00001355/// Determines whether there is a user-defined conversion sequence
1356/// (C++ [over.ics.user]) that converts expression From to the type
1357/// ToType. If such a conversion exists, User will contain the
1358/// user-defined conversion sequence that performs such a conversion
1359/// and this routine will return true. Otherwise, this routine returns
1360/// false and User is unspecified.
1361///
1362/// \param AllowConversionFunctions true if the conversion should
1363/// consider conversion functions at all. If false, only constructors
1364/// will be considered.
1365///
1366/// \param AllowExplicit true if the conversion should consider C++0x
1367/// "explicit" conversion functions as well as non-explicit conversion
1368/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001369///
1370/// \param ForceRValue true if the expression should be treated as an rvalue
1371/// for overload resolution.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001372/// \param UserCast true if looking for user defined conversion for a static
1373/// cast.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001374Sema::OverloadingResult Sema::IsUserDefinedConversion(
1375 Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001376 UserDefinedConversionSequence& User,
Fariborz Jahanian19c73282009-09-15 00:10:11 +00001377 OverloadCandidateSet& CandidateSet,
Douglas Gregor576e98c2009-01-30 23:27:23 +00001378 bool AllowConversionFunctions,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001379 bool AllowExplicit, bool ForceRValue,
1380 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001381 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001382 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1383 // We're not going to find any constructors.
1384 } else if (CXXRecordDecl *ToRecordDecl
1385 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001386 // C++ [over.match.ctor]p1:
1387 // When objects of class type are direct-initialized (8.5), or
1388 // copy-initialized from an expression of the same or a
1389 // derived class type (8.5), overload resolution selects the
1390 // constructor. [...] For copy-initialization, the candidate
1391 // functions are all the converting constructors (12.3.1) of
1392 // that class. The argument list is the expression-list within
1393 // the parentheses of the initializer.
Douglas Gregor379d84b2009-11-13 18:44:21 +00001394 bool SuppressUserConversions = !UserCast;
1395 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1396 IsDerivedFrom(From->getType(), ToType)) {
1397 SuppressUserConversions = false;
1398 AllowConversionFunctions = false;
1399 }
1400
Mike Stump11289f42009-09-09 15:08:12 +00001401 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001402 = Context.DeclarationNames.getCXXConstructorName(
1403 Context.getCanonicalType(ToType).getUnqualifiedType());
1404 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001405 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001406 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001407 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001408 // Find the constructor (which may be a template).
1409 CXXConstructorDecl *Constructor = 0;
1410 FunctionTemplateDecl *ConstructorTmpl
1411 = dyn_cast<FunctionTemplateDecl>(*Con);
1412 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001413 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001414 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1415 else
1416 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001417
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001418 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001419 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001420 if (ConstructorTmpl)
John McCall6b51f282009-11-23 01:53:49 +00001421 AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
1422 &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001423 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001424 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001425 // Allow one user-defined conversion when user specifies a
1426 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001427 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001428 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001429 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001430 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001431 }
1432 }
1433
Douglas Gregor576e98c2009-01-30 23:27:23 +00001434 if (!AllowConversionFunctions) {
1435 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001436 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1437 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001438 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001439 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001440 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001441 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001442 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001443 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1444 // Add all of the conversion functions as candidates.
John McCalld14a8642009-11-21 08:51:07 +00001445 const UnresolvedSet *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001446 = FromRecordDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00001447 for (UnresolvedSet::iterator I = Conversions->begin(),
1448 E = Conversions->end(); I != E; ++I) {
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001449 CXXConversionDecl *Conv;
1450 FunctionTemplateDecl *ConvTemplate;
John McCalld14a8642009-11-21 08:51:07 +00001451 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001452 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1453 else
John McCalld14a8642009-11-21 08:51:07 +00001454 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001455
1456 if (AllowExplicit || !Conv->isExplicit()) {
1457 if (ConvTemplate)
1458 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1459 CandidateSet);
1460 else
1461 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1462 }
1463 }
1464 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001465 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001466
1467 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001468 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001469 case OR_Success:
1470 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001471 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001472 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1473 // C++ [over.ics.user]p1:
1474 // If the user-defined conversion is specified by a
1475 // constructor (12.3.1), the initial standard conversion
1476 // sequence converts the source type to the type required by
1477 // the argument of the constructor.
1478 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001479 QualType ThisType = Constructor->getThisType(Context);
Fariborz Jahanian55824512009-11-06 00:23:08 +00001480 if (Best->Conversions[0].ConversionKind ==
1481 ImplicitConversionSequence::EllipsisConversion)
1482 User.EllipsisConversion = true;
1483 else {
1484 User.Before = Best->Conversions[0].Standard;
1485 User.EllipsisConversion = false;
1486 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001487 User.ConversionFunction = Constructor;
1488 User.After.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00001489 User.After.FromTypePtr
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001490 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001491 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001492 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001493 } else if (CXXConversionDecl *Conversion
1494 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1495 // C++ [over.ics.user]p1:
1496 //
1497 // [...] If the user-defined conversion is specified by a
1498 // conversion function (12.3.2), the initial standard
1499 // conversion sequence converts the source type to the
1500 // implicit object parameter of the conversion function.
1501 User.Before = Best->Conversions[0].Standard;
1502 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001503 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001504
1505 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001506 // The second standard conversion sequence converts the
1507 // result of the user-defined conversion to the target type
1508 // for the sequence. Since an implicit conversion sequence
1509 // is an initialization, the special rules for
1510 // initialization by user-defined conversion apply when
1511 // selecting the best user-defined conversion for a
1512 // user-defined conversion sequence (see 13.3.3 and
1513 // 13.3.3.1).
1514 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001515 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001516 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001517 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001518 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001519 }
Mike Stump11289f42009-09-09 15:08:12 +00001520
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001521 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001522 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001523 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001524 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001525 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001526
1527 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001528 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001529 }
1530
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001531 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001532}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001533
1534bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001535Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001536 ImplicitConversionSequence ICS;
1537 OverloadCandidateSet CandidateSet;
1538 OverloadingResult OvResult =
1539 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1540 CandidateSet, true, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001541 if (OvResult == OR_Ambiguous)
1542 Diag(From->getSourceRange().getBegin(),
1543 diag::err_typecheck_ambiguous_condition)
1544 << From->getType() << ToType << From->getSourceRange();
1545 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1546 Diag(From->getSourceRange().getBegin(),
1547 diag::err_typecheck_nonviable_condition)
1548 << From->getType() << ToType << From->getSourceRange();
1549 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001550 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00001551 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001552 return true;
1553}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001554
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001555/// CompareImplicitConversionSequences - Compare two implicit
1556/// conversion sequences to determine whether one is better than the
1557/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001558ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001559Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1560 const ImplicitConversionSequence& ICS2)
1561{
1562 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1563 // conversion sequences (as defined in 13.3.3.1)
1564 // -- a standard conversion sequence (13.3.3.1.1) is a better
1565 // conversion sequence than a user-defined conversion sequence or
1566 // an ellipsis conversion sequence, and
1567 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1568 // conversion sequence than an ellipsis conversion sequence
1569 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001570 //
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001571 if (ICS1.ConversionKind < ICS2.ConversionKind)
1572 return ImplicitConversionSequence::Better;
1573 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1574 return ImplicitConversionSequence::Worse;
1575
1576 // Two implicit conversion sequences of the same form are
1577 // indistinguishable conversion sequences unless one of the
1578 // following rules apply: (C++ 13.3.3.2p3):
1579 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1580 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump11289f42009-09-09 15:08:12 +00001581 else if (ICS1.ConversionKind ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001582 ImplicitConversionSequence::UserDefinedConversion) {
1583 // User-defined conversion sequence U1 is a better conversion
1584 // sequence than another user-defined conversion sequence U2 if
1585 // they contain the same user-defined conversion function or
1586 // constructor and if the second standard conversion sequence of
1587 // U1 is better than the second standard conversion sequence of
1588 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001589 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001590 ICS2.UserDefined.ConversionFunction)
1591 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1592 ICS2.UserDefined.After);
1593 }
1594
1595 return ImplicitConversionSequence::Indistinguishable;
1596}
1597
1598/// CompareStandardConversionSequences - Compare two standard
1599/// conversion sequences to determine whether one is better than the
1600/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001601ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001602Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1603 const StandardConversionSequence& SCS2)
1604{
1605 // Standard conversion sequence S1 is a better conversion sequence
1606 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1607
1608 // -- S1 is a proper subsequence of S2 (comparing the conversion
1609 // sequences in the canonical form defined by 13.3.3.1.1,
1610 // excluding any Lvalue Transformation; the identity conversion
1611 // sequence is considered to be a subsequence of any
1612 // non-identity conversion sequence) or, if not that,
1613 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1614 // Neither is a proper subsequence of the other. Do nothing.
1615 ;
1616 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1617 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001618 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001619 SCS1.Third == ICK_Identity))
1620 // SCS1 is a proper subsequence of SCS2.
1621 return ImplicitConversionSequence::Better;
1622 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1623 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001624 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001625 SCS2.Third == ICK_Identity))
1626 // SCS2 is a proper subsequence of SCS1.
1627 return ImplicitConversionSequence::Worse;
1628
1629 // -- the rank of S1 is better than the rank of S2 (by the rules
1630 // defined below), or, if not that,
1631 ImplicitConversionRank Rank1 = SCS1.getRank();
1632 ImplicitConversionRank Rank2 = SCS2.getRank();
1633 if (Rank1 < Rank2)
1634 return ImplicitConversionSequence::Better;
1635 else if (Rank2 < Rank1)
1636 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001637
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001638 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1639 // are indistinguishable unless one of the following rules
1640 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001641
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001642 // A conversion that is not a conversion of a pointer, or
1643 // pointer to member, to bool is better than another conversion
1644 // that is such a conversion.
1645 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1646 return SCS2.isPointerConversionToBool()
1647 ? ImplicitConversionSequence::Better
1648 : ImplicitConversionSequence::Worse;
1649
Douglas Gregor5c407d92008-10-23 00:40:37 +00001650 // C++ [over.ics.rank]p4b2:
1651 //
1652 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001653 // conversion of B* to A* is better than conversion of B* to
1654 // void*, and conversion of A* to void* is better than conversion
1655 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001656 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001657 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001658 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001659 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001660 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1661 // Exactly one of the conversion sequences is a conversion to
1662 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001663 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1664 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001665 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1666 // Neither conversion sequence converts to a void pointer; compare
1667 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001668 if (ImplicitConversionSequence::CompareKind DerivedCK
1669 = CompareDerivedToBaseConversions(SCS1, SCS2))
1670 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001671 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1672 // Both conversion sequences are conversions to void
1673 // pointers. Compare the source types to determine if there's an
1674 // inheritance relationship in their sources.
1675 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1676 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1677
1678 // Adjust the types we're converting from via the array-to-pointer
1679 // conversion, if we need to.
1680 if (SCS1.First == ICK_Array_To_Pointer)
1681 FromType1 = Context.getArrayDecayedType(FromType1);
1682 if (SCS2.First == ICK_Array_To_Pointer)
1683 FromType2 = Context.getArrayDecayedType(FromType2);
1684
Mike Stump11289f42009-09-09 15:08:12 +00001685 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001686 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001687 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001688 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001689
1690 if (IsDerivedFrom(FromPointee2, FromPointee1))
1691 return ImplicitConversionSequence::Better;
1692 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1693 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001694
1695 // Objective-C++: If one interface is more specific than the
1696 // other, it is the better one.
John McCall9dd450b2009-09-21 23:43:11 +00001697 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1698 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001699 if (FromIface1 && FromIface1) {
1700 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1701 return ImplicitConversionSequence::Better;
1702 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1703 return ImplicitConversionSequence::Worse;
1704 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001705 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001706
1707 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1708 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001709 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001710 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001711 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001712
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001713 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001714 // C++0x [over.ics.rank]p3b4:
1715 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1716 // implicit object parameter of a non-static member function declared
1717 // without a ref-qualifier, and S1 binds an rvalue reference to an
1718 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001719 // FIXME: We don't know if we're dealing with the implicit object parameter,
1720 // or if the member function in this case has a ref qualifier.
1721 // (Of course, we don't have ref qualifiers yet.)
1722 if (SCS1.RRefBinding != SCS2.RRefBinding)
1723 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1724 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001725
1726 // C++ [over.ics.rank]p3b4:
1727 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1728 // which the references refer are the same type except for
1729 // top-level cv-qualifiers, and the type to which the reference
1730 // initialized by S2 refers is more cv-qualified than the type
1731 // to which the reference initialized by S1 refers.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001732 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1733 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001734 T1 = Context.getCanonicalType(T1);
1735 T2 = Context.getCanonicalType(T2);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001736 if (Context.hasSameUnqualifiedType(T1, T2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001737 if (T2.isMoreQualifiedThan(T1))
1738 return ImplicitConversionSequence::Better;
1739 else if (T1.isMoreQualifiedThan(T2))
1740 return ImplicitConversionSequence::Worse;
1741 }
1742 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001743
1744 return ImplicitConversionSequence::Indistinguishable;
1745}
1746
1747/// CompareQualificationConversions - Compares two standard conversion
1748/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001749/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1750ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001751Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001752 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001753 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001754 // -- S1 and S2 differ only in their qualification conversion and
1755 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1756 // cv-qualification signature of type T1 is a proper subset of
1757 // the cv-qualification signature of type T2, and S1 is not the
1758 // deprecated string literal array-to-pointer conversion (4.2).
1759 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1760 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1761 return ImplicitConversionSequence::Indistinguishable;
1762
1763 // FIXME: the example in the standard doesn't use a qualification
1764 // conversion (!)
1765 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1766 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1767 T1 = Context.getCanonicalType(T1);
1768 T2 = Context.getCanonicalType(T2);
1769
1770 // If the types are the same, we won't learn anything by unwrapped
1771 // them.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001772 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001773 return ImplicitConversionSequence::Indistinguishable;
1774
Mike Stump11289f42009-09-09 15:08:12 +00001775 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001776 = ImplicitConversionSequence::Indistinguishable;
1777 while (UnwrapSimilarPointerTypes(T1, T2)) {
1778 // Within each iteration of the loop, we check the qualifiers to
1779 // determine if this still looks like a qualification
1780 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001781 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001782 // until there are no more pointers or pointers-to-members left
1783 // to unwrap. This essentially mimics what
1784 // IsQualificationConversion does, but here we're checking for a
1785 // strict subset of qualifiers.
1786 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1787 // The qualifiers are the same, so this doesn't tell us anything
1788 // about how the sequences rank.
1789 ;
1790 else if (T2.isMoreQualifiedThan(T1)) {
1791 // T1 has fewer qualifiers, so it could be the better sequence.
1792 if (Result == ImplicitConversionSequence::Worse)
1793 // Neither has qualifiers that are a subset of the other's
1794 // qualifiers.
1795 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001796
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001797 Result = ImplicitConversionSequence::Better;
1798 } else if (T1.isMoreQualifiedThan(T2)) {
1799 // T2 has fewer qualifiers, so it could be the better sequence.
1800 if (Result == ImplicitConversionSequence::Better)
1801 // Neither has qualifiers that are a subset of the other's
1802 // qualifiers.
1803 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001804
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001805 Result = ImplicitConversionSequence::Worse;
1806 } else {
1807 // Qualifiers are disjoint.
1808 return ImplicitConversionSequence::Indistinguishable;
1809 }
1810
1811 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001812 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001813 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001814 }
1815
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001816 // Check that the winning standard conversion sequence isn't using
1817 // the deprecated string literal array to pointer conversion.
1818 switch (Result) {
1819 case ImplicitConversionSequence::Better:
1820 if (SCS1.Deprecated)
1821 Result = ImplicitConversionSequence::Indistinguishable;
1822 break;
1823
1824 case ImplicitConversionSequence::Indistinguishable:
1825 break;
1826
1827 case ImplicitConversionSequence::Worse:
1828 if (SCS2.Deprecated)
1829 Result = ImplicitConversionSequence::Indistinguishable;
1830 break;
1831 }
1832
1833 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001834}
1835
Douglas Gregor5c407d92008-10-23 00:40:37 +00001836/// CompareDerivedToBaseConversions - Compares two standard conversion
1837/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001838/// various kinds of derived-to-base conversions (C++
1839/// [over.ics.rank]p4b3). As part of these checks, we also look at
1840/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001841ImplicitConversionSequence::CompareKind
1842Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1843 const StandardConversionSequence& SCS2) {
1844 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1845 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1846 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1847 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1848
1849 // Adjust the types we're converting from via the array-to-pointer
1850 // conversion, if we need to.
1851 if (SCS1.First == ICK_Array_To_Pointer)
1852 FromType1 = Context.getArrayDecayedType(FromType1);
1853 if (SCS2.First == ICK_Array_To_Pointer)
1854 FromType2 = Context.getArrayDecayedType(FromType2);
1855
1856 // Canonicalize all of the types.
1857 FromType1 = Context.getCanonicalType(FromType1);
1858 ToType1 = Context.getCanonicalType(ToType1);
1859 FromType2 = Context.getCanonicalType(FromType2);
1860 ToType2 = Context.getCanonicalType(ToType2);
1861
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001862 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001863 //
1864 // If class B is derived directly or indirectly from class A and
1865 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001866 //
1867 // For Objective-C, we let A, B, and C also be Objective-C
1868 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001869
1870 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00001871 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00001872 SCS2.Second == ICK_Pointer_Conversion &&
1873 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1874 FromType1->isPointerType() && FromType2->isPointerType() &&
1875 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001876 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001877 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001878 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001879 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001880 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001881 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001882 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001883 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001884
John McCall9dd450b2009-09-21 23:43:11 +00001885 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1886 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1887 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1888 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001889
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001890 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00001891 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1892 if (IsDerivedFrom(ToPointee1, ToPointee2))
1893 return ImplicitConversionSequence::Better;
1894 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1895 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001896
1897 if (ToIface1 && ToIface2) {
1898 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1899 return ImplicitConversionSequence::Better;
1900 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1901 return ImplicitConversionSequence::Worse;
1902 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001903 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001904
1905 // -- conversion of B* to A* is better than conversion of C* to A*,
1906 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1907 if (IsDerivedFrom(FromPointee2, FromPointee1))
1908 return ImplicitConversionSequence::Better;
1909 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1910 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00001911
Douglas Gregor237f96c2008-11-26 23:31:11 +00001912 if (FromIface1 && FromIface2) {
1913 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1914 return ImplicitConversionSequence::Better;
1915 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1916 return ImplicitConversionSequence::Worse;
1917 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001918 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001919 }
1920
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001921 // Compare based on reference bindings.
1922 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1923 SCS1.Second == ICK_Derived_To_Base) {
1924 // -- binding of an expression of type C to a reference of type
1925 // B& is better than binding an expression of type C to a
1926 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001927 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1928 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001929 if (IsDerivedFrom(ToType1, ToType2))
1930 return ImplicitConversionSequence::Better;
1931 else if (IsDerivedFrom(ToType2, ToType1))
1932 return ImplicitConversionSequence::Worse;
1933 }
1934
Douglas Gregor2fe98832008-11-03 19:09:14 +00001935 // -- binding of an expression of type B to a reference of type
1936 // A& is better than binding an expression of type C to a
1937 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001938 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1939 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001940 if (IsDerivedFrom(FromType2, FromType1))
1941 return ImplicitConversionSequence::Better;
1942 else if (IsDerivedFrom(FromType1, FromType2))
1943 return ImplicitConversionSequence::Worse;
1944 }
1945 }
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00001946
1947 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00001948 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
1949 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
1950 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
1951 const MemberPointerType * FromMemPointer1 =
1952 FromType1->getAs<MemberPointerType>();
1953 const MemberPointerType * ToMemPointer1 =
1954 ToType1->getAs<MemberPointerType>();
1955 const MemberPointerType * FromMemPointer2 =
1956 FromType2->getAs<MemberPointerType>();
1957 const MemberPointerType * ToMemPointer2 =
1958 ToType2->getAs<MemberPointerType>();
1959 const Type *FromPointeeType1 = FromMemPointer1->getClass();
1960 const Type *ToPointeeType1 = ToMemPointer1->getClass();
1961 const Type *FromPointeeType2 = FromMemPointer2->getClass();
1962 const Type *ToPointeeType2 = ToMemPointer2->getClass();
1963 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
1964 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
1965 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
1966 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00001967 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00001968 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1969 if (IsDerivedFrom(ToPointee1, ToPointee2))
1970 return ImplicitConversionSequence::Worse;
1971 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1972 return ImplicitConversionSequence::Better;
1973 }
1974 // conversion of B::* to C::* is better than conversion of A::* to C::*
1975 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
1976 if (IsDerivedFrom(FromPointee1, FromPointee2))
1977 return ImplicitConversionSequence::Better;
1978 else if (IsDerivedFrom(FromPointee2, FromPointee1))
1979 return ImplicitConversionSequence::Worse;
1980 }
1981 }
1982
Douglas Gregor2fe98832008-11-03 19:09:14 +00001983 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1984 SCS1.Second == ICK_Derived_To_Base) {
1985 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001986 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1987 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00001988 if (IsDerivedFrom(ToType1, ToType2))
1989 return ImplicitConversionSequence::Better;
1990 else if (IsDerivedFrom(ToType2, ToType1))
1991 return ImplicitConversionSequence::Worse;
1992 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001993
Douglas Gregor2fe98832008-11-03 19:09:14 +00001994 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001995 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1996 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00001997 if (IsDerivedFrom(FromType2, FromType1))
1998 return ImplicitConversionSequence::Better;
1999 else if (IsDerivedFrom(FromType1, FromType2))
2000 return ImplicitConversionSequence::Worse;
2001 }
2002 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002003
Douglas Gregor5c407d92008-10-23 00:40:37 +00002004 return ImplicitConversionSequence::Indistinguishable;
2005}
2006
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002007/// TryCopyInitialization - Try to copy-initialize a value of type
2008/// ToType from the expression From. Return the implicit conversion
2009/// sequence required to pass this argument, which may be a bad
2010/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002011/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00002012/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2013/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00002014ImplicitConversionSequence
2015Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002016 bool SuppressUserConversions, bool ForceRValue,
2017 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002018 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002019 ImplicitConversionSequence ICS;
Mike Stump11289f42009-09-09 15:08:12 +00002020 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002021 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002022 SuppressUserConversions,
2023 /*AllowExplicit=*/false,
2024 ForceRValue,
2025 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002026 return ICS;
2027 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002028 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002029 SuppressUserConversions,
2030 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002031 ForceRValue,
2032 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002033 }
2034}
2035
Sebastian Redl42e92c42009-04-12 17:16:29 +00002036/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2037/// the expression @p From. Returns true (and emits a diagnostic) if there was
2038/// an error, returns false if the initialization succeeded. Elidable should
2039/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2040/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002041bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002042 const char* Flavor, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002043 if (!getLangOptions().CPlusPlus) {
2044 // In C, argument passing is the same as performing an assignment.
2045 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002046
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002047 AssignConvertType ConvTy =
2048 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002049 if (ConvTy != Compatible &&
2050 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2051 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002052
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002053 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2054 FromType, From, Flavor);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002055 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002056
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002057 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002058 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002059 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002060 /*SuppressUserConversions=*/false,
2061 /*AllowExplicit=*/false,
2062 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002063
Sebastian Redl42e92c42009-04-12 17:16:29 +00002064 if (!PerformImplicitConversion(From, ToType, Flavor,
2065 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002066 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00002067 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002068 return Diag(From->getSourceRange().getBegin(),
2069 diag::err_typecheck_convert_incompatible)
2070 << ToType << From->getType() << Flavor << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002071 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002072}
2073
Douglas Gregor436424c2008-11-18 23:14:02 +00002074/// TryObjectArgumentInitialization - Try to initialize the object
2075/// parameter of the given member function (@c Method) from the
2076/// expression @p From.
2077ImplicitConversionSequence
2078Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
2079 QualType ClassType = Context.getTypeDeclType(Method->getParent());
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002080 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2081 // const volatile object.
2082 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2083 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2084 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002085
2086 // Set up the conversion sequence as a "bad" conversion, to allow us
2087 // to exit early.
2088 ImplicitConversionSequence ICS;
2089 ICS.Standard.setAsIdentityConversion();
2090 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2091
2092 // We need to have an object of class type.
2093 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002094 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002095 FromType = PT->getPointeeType();
2096
2097 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002098
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002099 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002100 // where X is the class of which the function is a member
2101 // (C++ [over.match.funcs]p4). However, when finding an implicit
2102 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002103 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002104 // (C++ [over.match.funcs]p5). We perform a simplified version of
2105 // reference binding here, that allows class rvalues to bind to
2106 // non-constant references.
2107
2108 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2109 // with the implicit object parameter (C++ [over.match.funcs]p5).
2110 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002111 if (ImplicitParamType.getCVRQualifiers()
2112 != FromTypeCanon.getLocalCVRQualifiers() &&
Douglas Gregor01df9462009-11-05 00:07:36 +00002113 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon))
Douglas Gregor436424c2008-11-18 23:14:02 +00002114 return ICS;
2115
2116 // Check that we have either the same type or a derived type. It
2117 // affects the conversion rank.
2118 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002119 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor436424c2008-11-18 23:14:02 +00002120 ICS.Standard.Second = ICK_Identity;
2121 else if (IsDerivedFrom(FromType, ClassType))
2122 ICS.Standard.Second = ICK_Derived_To_Base;
2123 else
2124 return ICS;
2125
2126 // Success. Mark this as a reference binding.
2127 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2128 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2129 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2130 ICS.Standard.ReferenceBinding = true;
2131 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002132 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002133 return ICS;
2134}
2135
2136/// PerformObjectArgumentInitialization - Perform initialization of
2137/// the implicit object parameter for the given Method with the given
2138/// expression.
2139bool
2140Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002141 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002142 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002143 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002144
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002145 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002146 FromRecordType = PT->getPointeeType();
2147 DestType = Method->getThisType(Context);
2148 } else {
2149 FromRecordType = From->getType();
2150 DestType = ImplicitParamRecordType;
2151 }
2152
Mike Stump11289f42009-09-09 15:08:12 +00002153 ImplicitConversionSequence ICS
Douglas Gregor436424c2008-11-18 23:14:02 +00002154 = TryObjectArgumentInitialization(From, Method);
2155 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2156 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002157 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002158 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002159
Douglas Gregor436424c2008-11-18 23:14:02 +00002160 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002161 CheckDerivedToBaseConversion(FromRecordType,
2162 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002163 From->getSourceRange().getBegin(),
2164 From->getSourceRange()))
2165 return true;
2166
Mike Stump11289f42009-09-09 15:08:12 +00002167 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002168 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002169 return false;
2170}
2171
Douglas Gregor5fb53972009-01-14 15:45:31 +00002172/// TryContextuallyConvertToBool - Attempt to contextually convert the
2173/// expression From to bool (C++0x [conv]p3).
2174ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002175 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002176 // FIXME: Are these flags correct?
2177 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002178 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002179 /*ForceRValue=*/false,
2180 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002181}
2182
2183/// PerformContextuallyConvertToBool - Perform a contextual conversion
2184/// of the expression From to bool (C++0x [conv]p3).
2185bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2186 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2187 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2188 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002189
Fariborz Jahanian76197412009-11-18 18:26:29 +00002190 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002191 return Diag(From->getSourceRange().getBegin(),
2192 diag::err_typecheck_bool_condition)
2193 << From->getType() << From->getSourceRange();
2194 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002195}
2196
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002197/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002198/// candidate functions, using the given function call arguments. If
2199/// @p SuppressUserConversions, then don't allow user-defined
2200/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002201/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2202/// hacky way to implement the overloading rules for elidable copy
2203/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002204///
2205/// \para PartialOverloading true if we are performing "partial" overloading
2206/// based on an incomplete set of function arguments. This feature is used by
2207/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002208void
2209Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002210 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002211 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002212 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002213 bool ForceRValue,
2214 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002215 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002216 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002217 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002218 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002219 "Use AddConversionCandidate for conversion functions");
Mike Stump11289f42009-09-09 15:08:12 +00002220 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002221 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002222
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002223 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002224 if (!isa<CXXConstructorDecl>(Method)) {
2225 // If we get here, it's because we're calling a member function
2226 // that is named without a member access expression (e.g.,
2227 // "this->f") that was either written explicitly or created
2228 // implicitly. This can happen with a qualified call to a member
2229 // function, e.g., X::f(). We use a NULL object as the implied
2230 // object argument (C++ [over.call.func]p3).
Mike Stump11289f42009-09-09 15:08:12 +00002231 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002232 SuppressUserConversions, ForceRValue);
2233 return;
2234 }
2235 // We treat a constructor like a non-member function, since its object
2236 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002237 }
2238
Douglas Gregorff7028a2009-11-13 23:59:09 +00002239 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002240 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002241
Douglas Gregor27381f32009-11-23 12:27:39 +00002242 // Overload resolution is always an unevaluated context.
2243 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2244
Douglas Gregorffe14e32009-11-14 01:20:54 +00002245 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2246 // C++ [class.copy]p3:
2247 // A member function template is never instantiated to perform the copy
2248 // of a class object to an object of its class type.
2249 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2250 if (NumArgs == 1 &&
2251 Constructor->isCopyConstructorLikeSpecialization() &&
2252 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2253 return;
2254 }
2255
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002256 // Add this candidate
2257 CandidateSet.push_back(OverloadCandidate());
2258 OverloadCandidate& Candidate = CandidateSet.back();
2259 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002260 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002261 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002262 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002263
2264 unsigned NumArgsInProto = Proto->getNumArgs();
2265
2266 // (C++ 13.3.2p2): A candidate function having fewer than m
2267 // parameters is viable only if it has an ellipsis in its parameter
2268 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002269 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2270 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002271 Candidate.Viable = false;
2272 return;
2273 }
2274
2275 // (C++ 13.3.2p2): A candidate function having more than m parameters
2276 // is viable only if the (m+1)st parameter has a default argument
2277 // (8.3.6). For the purposes of overload resolution, the
2278 // parameter list is truncated on the right, so that there are
2279 // exactly m parameters.
2280 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002281 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002282 // Not enough arguments.
2283 Candidate.Viable = false;
2284 return;
2285 }
2286
2287 // Determine the implicit conversion sequences for each of the
2288 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002289 Candidate.Conversions.resize(NumArgs);
2290 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2291 if (ArgIdx < NumArgsInProto) {
2292 // (C++ 13.3.2p3): for F to be a viable function, there shall
2293 // exist for each argument an implicit conversion sequence
2294 // (13.3.3.1) that converts that argument to the corresponding
2295 // parameter of F.
2296 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002297 Candidate.Conversions[ArgIdx]
2298 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002299 SuppressUserConversions, ForceRValue,
2300 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002301 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002302 == ImplicitConversionSequence::BadConversion) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002303 // 13.3.3.1-p10 If several different sequences of conversions exist that
2304 // each convert the argument to the parameter type, the implicit conversion
2305 // sequence associated with the parameter is defined to be the unique conversion
2306 // sequence designated the ambiguous conversion sequence. For the purpose of
2307 // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2308 // conversion sequence is treated as a user-defined sequence that is
2309 // indistinguishable from any other user-defined conversion sequence
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002310 if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002311 Candidate.Conversions[ArgIdx].ConversionKind =
2312 ImplicitConversionSequence::UserDefinedConversion;
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002313 // Set the conversion function to one of them. As due to ambiguity,
2314 // they carry the same weight and is needed for overload resolution
2315 // later.
2316 Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2317 Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2318 }
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002319 else {
2320 Candidate.Viable = false;
2321 break;
2322 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002323 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002324 } else {
2325 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2326 // argument for which there is no corresponding parameter is
2327 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002328 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002329 = ImplicitConversionSequence::EllipsisConversion;
2330 }
2331 }
2332}
2333
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002334/// \brief Add all of the function declarations in the given function set to
2335/// the overload canddiate set.
2336void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2337 Expr **Args, unsigned NumArgs,
2338 OverloadCandidateSet& CandidateSet,
2339 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002340 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002341 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002342 F != FEnd; ++F) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002343 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2344 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2345 AddMethodCandidate(cast<CXXMethodDecl>(FD),
2346 Args[0], Args + 1, NumArgs - 1,
2347 CandidateSet, SuppressUserConversions);
2348 else
2349 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2350 SuppressUserConversions);
2351 } else {
2352 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2353 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2354 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2355 AddMethodTemplateCandidate(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00002356 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002357 Args[0], Args + 1, NumArgs - 1,
2358 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002359 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002360 else
2361 AddTemplateOverloadCandidate(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00002362 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002363 Args, NumArgs, CandidateSet,
2364 SuppressUserConversions);
2365 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002366 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002367}
2368
John McCallf0f1cf02009-11-17 07:50:12 +00002369/// AddMethodCandidate - Adds a named decl (which is some kind of
2370/// method) as a method candidate to the given overload set.
2371void Sema::AddMethodCandidate(NamedDecl *Decl, Expr *Object,
2372 Expr **Args, unsigned NumArgs,
2373 OverloadCandidateSet& CandidateSet,
2374 bool SuppressUserConversions, bool ForceRValue) {
2375
2376 // FIXME: use this
2377 //DeclContext *ActingContext = Decl->getDeclContext();
2378
2379 if (isa<UsingShadowDecl>(Decl))
2380 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2381
2382 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2383 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2384 "Expected a member function template");
John McCall6b51f282009-11-23 01:53:49 +00002385 AddMethodTemplateCandidate(TD, /*ExplicitArgs*/ 0,
John McCallf0f1cf02009-11-17 07:50:12 +00002386 Object, Args, NumArgs,
2387 CandidateSet,
2388 SuppressUserConversions,
2389 ForceRValue);
2390 } else {
2391 AddMethodCandidate(cast<CXXMethodDecl>(Decl), Object, Args, NumArgs,
2392 CandidateSet, SuppressUserConversions, ForceRValue);
2393 }
2394}
2395
Douglas Gregor436424c2008-11-18 23:14:02 +00002396/// AddMethodCandidate - Adds the given C++ member function to the set
2397/// of candidate functions, using the given function call arguments
2398/// and the object argument (@c Object). For example, in a call
2399/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2400/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2401/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002402/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2403/// a slightly hacky way to implement the overloading rules for elidable copy
2404/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002405void
Douglas Gregor436424c2008-11-18 23:14:02 +00002406Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2407 Expr **Args, unsigned NumArgs,
2408 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002409 bool SuppressUserConversions, bool ForceRValue) {
2410 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002411 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002412 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002413 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor436424c2008-11-18 23:14:02 +00002414 "Use AddConversionCandidate for conversion functions");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002415 assert(!isa<CXXConstructorDecl>(Method) &&
2416 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002417
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002418 if (!CandidateSet.isNewCandidate(Method))
2419 return;
2420
Douglas Gregor27381f32009-11-23 12:27:39 +00002421 // Overload resolution is always an unevaluated context.
2422 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2423
Douglas Gregor436424c2008-11-18 23:14:02 +00002424 // Add this candidate
2425 CandidateSet.push_back(OverloadCandidate());
2426 OverloadCandidate& Candidate = CandidateSet.back();
2427 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002428 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002429 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002430
2431 unsigned NumArgsInProto = Proto->getNumArgs();
2432
2433 // (C++ 13.3.2p2): A candidate function having fewer than m
2434 // parameters is viable only if it has an ellipsis in its parameter
2435 // list (8.3.5).
2436 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2437 Candidate.Viable = false;
2438 return;
2439 }
2440
2441 // (C++ 13.3.2p2): A candidate function having more than m parameters
2442 // is viable only if the (m+1)st parameter has a default argument
2443 // (8.3.6). For the purposes of overload resolution, the
2444 // parameter list is truncated on the right, so that there are
2445 // exactly m parameters.
2446 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2447 if (NumArgs < MinRequiredArgs) {
2448 // Not enough arguments.
2449 Candidate.Viable = false;
2450 return;
2451 }
2452
2453 Candidate.Viable = true;
2454 Candidate.Conversions.resize(NumArgs + 1);
2455
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002456 if (Method->isStatic() || !Object)
2457 // The implicit object argument is ignored.
2458 Candidate.IgnoreObjectArgument = true;
2459 else {
2460 // Determine the implicit conversion sequence for the object
2461 // parameter.
2462 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
Mike Stump11289f42009-09-09 15:08:12 +00002463 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002464 == ImplicitConversionSequence::BadConversion) {
2465 Candidate.Viable = false;
2466 return;
2467 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002468 }
2469
2470 // Determine the implicit conversion sequences for each of the
2471 // arguments.
2472 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2473 if (ArgIdx < NumArgsInProto) {
2474 // (C++ 13.3.2p3): for F to be a viable function, there shall
2475 // exist for each argument an implicit conversion sequence
2476 // (13.3.3.1) that converts that argument to the corresponding
2477 // parameter of F.
2478 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002479 Candidate.Conversions[ArgIdx + 1]
2480 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002481 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002482 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002483 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002484 == ImplicitConversionSequence::BadConversion) {
2485 Candidate.Viable = false;
2486 break;
2487 }
2488 } else {
2489 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2490 // argument for which there is no corresponding parameter is
2491 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002492 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002493 = ImplicitConversionSequence::EllipsisConversion;
2494 }
2495 }
2496}
2497
Douglas Gregor97628d62009-08-21 00:16:32 +00002498/// \brief Add a C++ member function template as a candidate to the candidate
2499/// set, using template argument deduction to produce an appropriate member
2500/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002501void
Douglas Gregor97628d62009-08-21 00:16:32 +00002502Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall6b51f282009-11-23 01:53:49 +00002503 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002504 Expr *Object, Expr **Args, unsigned NumArgs,
2505 OverloadCandidateSet& CandidateSet,
2506 bool SuppressUserConversions,
2507 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002508 if (!CandidateSet.isNewCandidate(MethodTmpl))
2509 return;
2510
Douglas Gregor97628d62009-08-21 00:16:32 +00002511 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002512 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002513 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002514 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002515 // candidate functions in the usual way.113) A given name can refer to one
2516 // or more function templates and also to a set of overloaded non-template
2517 // functions. In such a case, the candidate functions generated from each
2518 // function template are combined with the set of non-template candidate
2519 // functions.
2520 TemplateDeductionInfo Info(Context);
2521 FunctionDecl *Specialization = 0;
2522 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002523 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002524 Args, NumArgs, Specialization, Info)) {
2525 // FIXME: Record what happened with template argument deduction, so
2526 // that we can give the user a beautiful diagnostic.
2527 (void)Result;
2528 return;
2529 }
Mike Stump11289f42009-09-09 15:08:12 +00002530
Douglas Gregor97628d62009-08-21 00:16:32 +00002531 // Add the function template specialization produced by template argument
2532 // deduction as a candidate.
2533 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002534 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002535 "Specialization is not a member function?");
Mike Stump11289f42009-09-09 15:08:12 +00002536 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002537 CandidateSet, SuppressUserConversions, ForceRValue);
2538}
2539
Douglas Gregor05155d82009-08-21 23:19:43 +00002540/// \brief Add a C++ function template specialization as a candidate
2541/// in the candidate set, using template argument deduction to produce
2542/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002543void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002544Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00002545 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002546 Expr **Args, unsigned NumArgs,
2547 OverloadCandidateSet& CandidateSet,
2548 bool SuppressUserConversions,
2549 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002550 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2551 return;
2552
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002553 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002554 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002555 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002556 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002557 // candidate functions in the usual way.113) A given name can refer to one
2558 // or more function templates and also to a set of overloaded non-template
2559 // functions. In such a case, the candidate functions generated from each
2560 // function template are combined with the set of non-template candidate
2561 // functions.
2562 TemplateDeductionInfo Info(Context);
2563 FunctionDecl *Specialization = 0;
2564 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002565 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002566 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002567 // FIXME: Record what happened with template argument deduction, so
2568 // that we can give the user a beautiful diagnostic.
2569 (void)Result;
2570 return;
2571 }
Mike Stump11289f42009-09-09 15:08:12 +00002572
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002573 // Add the function template specialization produced by template argument
2574 // deduction as a candidate.
2575 assert(Specialization && "Missing function template specialization?");
2576 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2577 SuppressUserConversions, ForceRValue);
2578}
Mike Stump11289f42009-09-09 15:08:12 +00002579
Douglas Gregora1f013e2008-11-07 22:36:19 +00002580/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002581/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002582/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002583/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002584/// (which may or may not be the same type as the type that the
2585/// conversion function produces).
2586void
2587Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2588 Expr *From, QualType ToType,
2589 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002590 assert(!Conversion->getDescribedFunctionTemplate() &&
2591 "Conversion function templates use AddTemplateConversionCandidate");
2592
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002593 if (!CandidateSet.isNewCandidate(Conversion))
2594 return;
2595
Douglas Gregor27381f32009-11-23 12:27:39 +00002596 // Overload resolution is always an unevaluated context.
2597 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2598
Douglas Gregora1f013e2008-11-07 22:36:19 +00002599 // Add this candidate
2600 CandidateSet.push_back(OverloadCandidate());
2601 OverloadCandidate& Candidate = CandidateSet.back();
2602 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002603 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002604 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002605 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00002606 Candidate.FinalConversion.FromTypePtr
Douglas Gregora1f013e2008-11-07 22:36:19 +00002607 = Conversion->getConversionType().getAsOpaquePtr();
2608 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2609
Douglas Gregor436424c2008-11-18 23:14:02 +00002610 // Determine the implicit conversion sequence for the implicit
2611 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002612 Candidate.Viable = true;
2613 Candidate.Conversions.resize(1);
Douglas Gregor436424c2008-11-18 23:14:02 +00002614 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002615 // Conversion functions to a different type in the base class is visible in
2616 // the derived class. So, a derived to base conversion should not participate
2617 // in overload resolution.
2618 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2619 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump11289f42009-09-09 15:08:12 +00002620 if (Candidate.Conversions[0].ConversionKind
Douglas Gregora1f013e2008-11-07 22:36:19 +00002621 == ImplicitConversionSequence::BadConversion) {
2622 Candidate.Viable = false;
2623 return;
2624 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002625
2626 // We won't go through a user-define type conversion function to convert a
2627 // derived to base as such conversions are given Conversion Rank. They only
2628 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2629 QualType FromCanon
2630 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2631 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2632 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2633 Candidate.Viable = false;
2634 return;
2635 }
2636
Douglas Gregora1f013e2008-11-07 22:36:19 +00002637
2638 // To determine what the conversion from the result of calling the
2639 // conversion function to the type we're eventually trying to
2640 // convert to (ToType), we need to synthesize a call to the
2641 // conversion function and attempt copy initialization from it. This
2642 // makes sure that we get the right semantics with respect to
2643 // lvalues/rvalues and the type. Fortunately, we can allocate this
2644 // call on the stack and we don't need its arguments to be
2645 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002646 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002647 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00002648 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002649 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002650 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002651
2652 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002653 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2654 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002655 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002656 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002657 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002658 ImplicitConversionSequence ICS =
2659 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002660 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002661 /*ForceRValue=*/false,
2662 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002663
Douglas Gregora1f013e2008-11-07 22:36:19 +00002664 switch (ICS.ConversionKind) {
2665 case ImplicitConversionSequence::StandardConversion:
2666 Candidate.FinalConversion = ICS.Standard;
2667 break;
2668
2669 case ImplicitConversionSequence::BadConversion:
2670 Candidate.Viable = false;
2671 break;
2672
2673 default:
Mike Stump11289f42009-09-09 15:08:12 +00002674 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002675 "Can only end up with a standard conversion sequence or failure");
2676 }
2677}
2678
Douglas Gregor05155d82009-08-21 23:19:43 +00002679/// \brief Adds a conversion function template specialization
2680/// candidate to the overload set, using template argument deduction
2681/// to deduce the template arguments of the conversion function
2682/// template from the type that we are converting to (C++
2683/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002684void
Douglas Gregor05155d82009-08-21 23:19:43 +00002685Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2686 Expr *From, QualType ToType,
2687 OverloadCandidateSet &CandidateSet) {
2688 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2689 "Only conversion function templates permitted here");
2690
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002691 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2692 return;
2693
Douglas Gregor05155d82009-08-21 23:19:43 +00002694 TemplateDeductionInfo Info(Context);
2695 CXXConversionDecl *Specialization = 0;
2696 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002697 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002698 Specialization, Info)) {
2699 // FIXME: Record what happened with template argument deduction, so
2700 // that we can give the user a beautiful diagnostic.
2701 (void)Result;
2702 return;
2703 }
Mike Stump11289f42009-09-09 15:08:12 +00002704
Douglas Gregor05155d82009-08-21 23:19:43 +00002705 // Add the conversion function template specialization produced by
2706 // template argument deduction as a candidate.
2707 assert(Specialization && "Missing function template specialization?");
2708 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2709}
2710
Douglas Gregorab7897a2008-11-19 22:57:39 +00002711/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2712/// converts the given @c Object to a function pointer via the
2713/// conversion function @c Conversion, and then attempts to call it
2714/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2715/// the type of function that we'll eventually be calling.
2716void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002717 const FunctionProtoType *Proto,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002718 Expr *Object, Expr **Args, unsigned NumArgs,
2719 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002720 if (!CandidateSet.isNewCandidate(Conversion))
2721 return;
2722
Douglas Gregor27381f32009-11-23 12:27:39 +00002723 // Overload resolution is always an unevaluated context.
2724 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2725
Douglas Gregorab7897a2008-11-19 22:57:39 +00002726 CandidateSet.push_back(OverloadCandidate());
2727 OverloadCandidate& Candidate = CandidateSet.back();
2728 Candidate.Function = 0;
2729 Candidate.Surrogate = Conversion;
2730 Candidate.Viable = true;
2731 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002732 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002733 Candidate.Conversions.resize(NumArgs + 1);
2734
2735 // Determine the implicit conversion sequence for the implicit
2736 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002737 ImplicitConversionSequence ObjectInit
Douglas Gregorab7897a2008-11-19 22:57:39 +00002738 = TryObjectArgumentInitialization(Object, Conversion);
2739 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2740 Candidate.Viable = false;
2741 return;
2742 }
2743
2744 // The first conversion is actually a user-defined conversion whose
2745 // first conversion is ObjectInit's standard conversion (which is
2746 // effectively a reference binding). Record it as such.
Mike Stump11289f42009-09-09 15:08:12 +00002747 Candidate.Conversions[0].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002748 = ImplicitConversionSequence::UserDefinedConversion;
2749 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002750 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002751 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002752 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002753 = Candidate.Conversions[0].UserDefined.Before;
2754 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2755
Mike Stump11289f42009-09-09 15:08:12 +00002756 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002757 unsigned NumArgsInProto = Proto->getNumArgs();
2758
2759 // (C++ 13.3.2p2): A candidate function having fewer than m
2760 // parameters is viable only if it has an ellipsis in its parameter
2761 // list (8.3.5).
2762 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2763 Candidate.Viable = false;
2764 return;
2765 }
2766
2767 // Function types don't have any default arguments, so just check if
2768 // we have enough arguments.
2769 if (NumArgs < NumArgsInProto) {
2770 // Not enough arguments.
2771 Candidate.Viable = false;
2772 return;
2773 }
2774
2775 // Determine the implicit conversion sequences for each of the
2776 // arguments.
2777 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2778 if (ArgIdx < NumArgsInProto) {
2779 // (C++ 13.3.2p3): for F to be a viable function, there shall
2780 // exist for each argument an implicit conversion sequence
2781 // (13.3.3.1) that converts that argument to the corresponding
2782 // parameter of F.
2783 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002784 Candidate.Conversions[ArgIdx + 1]
2785 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002786 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002787 /*ForceRValue=*/false,
2788 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002789 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002790 == ImplicitConversionSequence::BadConversion) {
2791 Candidate.Viable = false;
2792 break;
2793 }
2794 } else {
2795 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2796 // argument for which there is no corresponding parameter is
2797 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002798 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002799 = ImplicitConversionSequence::EllipsisConversion;
2800 }
2801 }
2802}
2803
Mike Stump87c57ac2009-05-16 07:39:55 +00002804// FIXME: This will eventually be removed, once we've migrated all of the
2805// operator overloading logic over to the scheme used by binary operators, which
2806// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002807void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002808 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002809 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002810 OverloadCandidateSet& CandidateSet,
2811 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002812 FunctionSet Functions;
2813
2814 QualType T1 = Args[0]->getType();
2815 QualType T2;
2816 if (NumArgs > 1)
2817 T2 = Args[1]->getType();
2818
2819 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002820 if (S)
2821 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redlc057f422009-10-23 19:23:15 +00002822 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002823 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2824 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002825 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002826}
2827
2828/// \brief Add overload candidates for overloaded operators that are
2829/// member functions.
2830///
2831/// Add the overloaded operator candidates that are member functions
2832/// for the operator Op that was used in an operator expression such
2833/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2834/// CandidateSet will store the added overload candidates. (C++
2835/// [over.match.oper]).
2836void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2837 SourceLocation OpLoc,
2838 Expr **Args, unsigned NumArgs,
2839 OverloadCandidateSet& CandidateSet,
2840 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002841 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2842
2843 // C++ [over.match.oper]p3:
2844 // For a unary operator @ with an operand of a type whose
2845 // cv-unqualified version is T1, and for a binary operator @ with
2846 // a left operand of a type whose cv-unqualified version is T1 and
2847 // a right operand of a type whose cv-unqualified version is T2,
2848 // three sets of candidate functions, designated member
2849 // candidates, non-member candidates and built-in candidates, are
2850 // constructed as follows:
2851 QualType T1 = Args[0]->getType();
2852 QualType T2;
2853 if (NumArgs > 1)
2854 T2 = Args[1]->getType();
2855
2856 // -- If T1 is a class type, the set of member candidates is the
2857 // result of the qualified lookup of T1::operator@
2858 // (13.3.1.1.1); otherwise, the set of member candidates is
2859 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002860 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002861 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00002862 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002863 return;
Mike Stump11289f42009-09-09 15:08:12 +00002864
John McCall27b18f82009-11-17 02:14:36 +00002865 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
2866 LookupQualifiedName(Operators, T1Rec->getDecl());
2867 Operators.suppressDiagnostics();
2868
Mike Stump11289f42009-09-09 15:08:12 +00002869 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002870 OperEnd = Operators.end();
2871 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00002872 ++Oper)
2873 AddMethodCandidate(*Oper, Args[0], Args + 1, NumArgs - 1, CandidateSet,
2874 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00002875 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002876}
2877
Douglas Gregora11693b2008-11-12 17:17:38 +00002878/// AddBuiltinCandidate - Add a candidate for a built-in
2879/// operator. ResultTy and ParamTys are the result and parameter types
2880/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00002881/// arguments being passed to the candidate. IsAssignmentOperator
2882/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00002883/// operator. NumContextualBoolArguments is the number of arguments
2884/// (at the beginning of the argument list) that will be contextually
2885/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00002886void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00002887 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00002888 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002889 bool IsAssignmentOperator,
2890 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00002891 // Overload resolution is always an unevaluated context.
2892 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2893
Douglas Gregora11693b2008-11-12 17:17:38 +00002894 // Add this candidate
2895 CandidateSet.push_back(OverloadCandidate());
2896 OverloadCandidate& Candidate = CandidateSet.back();
2897 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00002898 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002899 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00002900 Candidate.BuiltinTypes.ResultTy = ResultTy;
2901 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2902 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2903
2904 // Determine the implicit conversion sequences for each of the
2905 // arguments.
2906 Candidate.Viable = true;
2907 Candidate.Conversions.resize(NumArgs);
2908 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00002909 // C++ [over.match.oper]p4:
2910 // For the built-in assignment operators, conversions of the
2911 // left operand are restricted as follows:
2912 // -- no temporaries are introduced to hold the left operand, and
2913 // -- no user-defined conversions are applied to the left
2914 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00002915 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00002916 //
2917 // We block these conversions by turning off user-defined
2918 // conversions, since that is the only way that initialization of
2919 // a reference to a non-class type can occur from something that
2920 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002921 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00002922 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00002923 "Contextual conversion to bool requires bool type");
2924 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2925 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002926 Candidate.Conversions[ArgIdx]
2927 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00002928 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00002929 /*ForceRValue=*/false,
2930 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002931 }
Mike Stump11289f42009-09-09 15:08:12 +00002932 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002933 == ImplicitConversionSequence::BadConversion) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002934 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002935 break;
2936 }
Douglas Gregora11693b2008-11-12 17:17:38 +00002937 }
2938}
2939
2940/// BuiltinCandidateTypeSet - A set of types that will be used for the
2941/// candidate operator functions for built-in operators (C++
2942/// [over.built]). The types are separated into pointer types and
2943/// enumeration types.
2944class BuiltinCandidateTypeSet {
2945 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002946 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00002947
2948 /// PointerTypes - The set of pointer types that will be used in the
2949 /// built-in candidates.
2950 TypeSet PointerTypes;
2951
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002952 /// MemberPointerTypes - The set of member pointer types that will be
2953 /// used in the built-in candidates.
2954 TypeSet MemberPointerTypes;
2955
Douglas Gregora11693b2008-11-12 17:17:38 +00002956 /// EnumerationTypes - The set of enumeration types that will be
2957 /// used in the built-in candidates.
2958 TypeSet EnumerationTypes;
2959
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002960 /// Sema - The semantic analysis instance where we are building the
2961 /// candidate type set.
2962 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00002963
Douglas Gregora11693b2008-11-12 17:17:38 +00002964 /// Context - The AST context in which we will build the type sets.
2965 ASTContext &Context;
2966
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00002967 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
2968 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002969 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002970
2971public:
2972 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002973 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00002974
Mike Stump11289f42009-09-09 15:08:12 +00002975 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002976 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00002977
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002978 void AddTypesConvertedFrom(QualType Ty,
2979 SourceLocation Loc,
2980 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00002981 bool AllowExplicitConversions,
2982 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00002983
2984 /// pointer_begin - First pointer type found;
2985 iterator pointer_begin() { return PointerTypes.begin(); }
2986
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002987 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002988 iterator pointer_end() { return PointerTypes.end(); }
2989
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002990 /// member_pointer_begin - First member pointer type found;
2991 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2992
2993 /// member_pointer_end - Past the last member pointer type found;
2994 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2995
Douglas Gregora11693b2008-11-12 17:17:38 +00002996 /// enumeration_begin - First enumeration type found;
2997 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2998
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002999 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003000 iterator enumeration_end() { return EnumerationTypes.end(); }
3001};
3002
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003003/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003004/// the set of pointer types along with any more-qualified variants of
3005/// that type. For example, if @p Ty is "int const *", this routine
3006/// will add "int const *", "int const volatile *", "int const
3007/// restrict *", and "int const volatile restrict *" to the set of
3008/// pointer types. Returns true if the add of @p Ty itself succeeded,
3009/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003010///
3011/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003012bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003013BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3014 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003015
Douglas Gregora11693b2008-11-12 17:17:38 +00003016 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003017 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003018 return false;
3019
John McCall8ccfcb52009-09-24 19:53:00 +00003020 const PointerType *PointerTy = Ty->getAs<PointerType>();
3021 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003022
John McCall8ccfcb52009-09-24 19:53:00 +00003023 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003024 // Don't add qualified variants of arrays. For one, they're not allowed
3025 // (the qualifier would sink to the element type), and for another, the
3026 // only overload situation where it matters is subscript or pointer +- int,
3027 // and those shouldn't have qualifier variants anyway.
3028 if (PointeeTy->isArrayType())
3029 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003030 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003031 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003032 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003033 bool hasVolatile = VisibleQuals.hasVolatile();
3034 bool hasRestrict = VisibleQuals.hasRestrict();
3035
John McCall8ccfcb52009-09-24 19:53:00 +00003036 // Iterate through all strict supersets of BaseCVR.
3037 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3038 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003039 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3040 // in the types.
3041 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3042 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003043 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3044 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003045 }
3046
3047 return true;
3048}
3049
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003050/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3051/// to the set of pointer types along with any more-qualified variants of
3052/// that type. For example, if @p Ty is "int const *", this routine
3053/// will add "int const *", "int const volatile *", "int const
3054/// restrict *", and "int const volatile restrict *" to the set of
3055/// pointer types. Returns true if the add of @p Ty itself succeeded,
3056/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003057///
3058/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003059bool
3060BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3061 QualType Ty) {
3062 // Insert this type.
3063 if (!MemberPointerTypes.insert(Ty))
3064 return false;
3065
John McCall8ccfcb52009-09-24 19:53:00 +00003066 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3067 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003068
John McCall8ccfcb52009-09-24 19:53:00 +00003069 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003070 // Don't add qualified variants of arrays. For one, they're not allowed
3071 // (the qualifier would sink to the element type), and for another, the
3072 // only overload situation where it matters is subscript or pointer +- int,
3073 // and those shouldn't have qualifier variants anyway.
3074 if (PointeeTy->isArrayType())
3075 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003076 const Type *ClassTy = PointerTy->getClass();
3077
3078 // Iterate through all strict supersets of the pointee type's CVR
3079 // qualifiers.
3080 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3081 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3082 if ((CVR | BaseCVR) != CVR) continue;
3083
3084 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3085 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003086 }
3087
3088 return true;
3089}
3090
Douglas Gregora11693b2008-11-12 17:17:38 +00003091/// AddTypesConvertedFrom - Add each of the types to which the type @p
3092/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003093/// primarily interested in pointer types and enumeration types. We also
3094/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003095/// AllowUserConversions is true if we should look at the conversion
3096/// functions of a class type, and AllowExplicitConversions if we
3097/// should also include the explicit conversion functions of a class
3098/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003099void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003100BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003101 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003102 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003103 bool AllowExplicitConversions,
3104 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003105 // Only deal with canonical types.
3106 Ty = Context.getCanonicalType(Ty);
3107
3108 // Look through reference types; they aren't part of the type of an
3109 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003110 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003111 Ty = RefTy->getPointeeType();
3112
3113 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003114 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003115
Sebastian Redl65ae2002009-11-05 16:36:20 +00003116 // If we're dealing with an array type, decay to the pointer.
3117 if (Ty->isArrayType())
3118 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3119
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003120 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003121 QualType PointeeTy = PointerTy->getPointeeType();
3122
3123 // Insert our type, and its more-qualified variants, into the set
3124 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003125 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003126 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003127 } else if (Ty->isMemberPointerType()) {
3128 // Member pointers are far easier, since the pointee can't be converted.
3129 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3130 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003131 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003132 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003133 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003134 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003135 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003136 // No conversion functions in incomplete types.
3137 return;
3138 }
Mike Stump11289f42009-09-09 15:08:12 +00003139
Douglas Gregora11693b2008-11-12 17:17:38 +00003140 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalld14a8642009-11-21 08:51:07 +00003141 const UnresolvedSet *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003142 = ClassDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00003143 for (UnresolvedSet::iterator I = Conversions->begin(),
3144 E = Conversions->end(); I != E; ++I) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003145
Mike Stump11289f42009-09-09 15:08:12 +00003146 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003147 // about which builtin types we can convert to.
John McCalld14a8642009-11-21 08:51:07 +00003148 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor05155d82009-08-21 23:19:43 +00003149 continue;
3150
John McCalld14a8642009-11-21 08:51:07 +00003151 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003152 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003153 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003154 VisibleQuals);
3155 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003156 }
3157 }
3158 }
3159}
3160
Douglas Gregor84605ae2009-08-24 13:43:27 +00003161/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3162/// the volatile- and non-volatile-qualified assignment operators for the
3163/// given type to the candidate set.
3164static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3165 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003166 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003167 unsigned NumArgs,
3168 OverloadCandidateSet &CandidateSet) {
3169 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003170
Douglas Gregor84605ae2009-08-24 13:43:27 +00003171 // T& operator=(T&, T)
3172 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3173 ParamTypes[1] = T;
3174 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3175 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003176
Douglas Gregor84605ae2009-08-24 13:43:27 +00003177 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3178 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003179 ParamTypes[0]
3180 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003181 ParamTypes[1] = T;
3182 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003183 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003184 }
3185}
Mike Stump11289f42009-09-09 15:08:12 +00003186
Sebastian Redl1054fae2009-10-25 17:03:50 +00003187/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3188/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003189static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3190 Qualifiers VRQuals;
3191 const RecordType *TyRec;
3192 if (const MemberPointerType *RHSMPType =
3193 ArgExpr->getType()->getAs<MemberPointerType>())
3194 TyRec = cast<RecordType>(RHSMPType->getClass());
3195 else
3196 TyRec = ArgExpr->getType()->getAs<RecordType>();
3197 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003198 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003199 VRQuals.addVolatile();
3200 VRQuals.addRestrict();
3201 return VRQuals;
3202 }
3203
3204 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalld14a8642009-11-21 08:51:07 +00003205 const UnresolvedSet *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003206 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003207
John McCalld14a8642009-11-21 08:51:07 +00003208 for (UnresolvedSet::iterator I = Conversions->begin(),
3209 E = Conversions->end(); I != E; ++I) {
3210 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003211 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3212 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3213 CanTy = ResTypeRef->getPointeeType();
3214 // Need to go down the pointer/mempointer chain and add qualifiers
3215 // as see them.
3216 bool done = false;
3217 while (!done) {
3218 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3219 CanTy = ResTypePtr->getPointeeType();
3220 else if (const MemberPointerType *ResTypeMPtr =
3221 CanTy->getAs<MemberPointerType>())
3222 CanTy = ResTypeMPtr->getPointeeType();
3223 else
3224 done = true;
3225 if (CanTy.isVolatileQualified())
3226 VRQuals.addVolatile();
3227 if (CanTy.isRestrictQualified())
3228 VRQuals.addRestrict();
3229 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3230 return VRQuals;
3231 }
3232 }
3233 }
3234 return VRQuals;
3235}
3236
Douglas Gregord08452f2008-11-19 15:42:04 +00003237/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3238/// operator overloads to the candidate set (C++ [over.built]), based
3239/// on the operator @p Op and the arguments given. For example, if the
3240/// operator is a binary '+', this routine might add "int
3241/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003242void
Mike Stump11289f42009-09-09 15:08:12 +00003243Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003244 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003245 Expr **Args, unsigned NumArgs,
3246 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003247 // The set of "promoted arithmetic types", which are the arithmetic
3248 // types are that preserved by promotion (C++ [over.built]p2). Note
3249 // that the first few of these types are the promoted integral
3250 // types; these types need to be first.
3251 // FIXME: What about complex?
3252 const unsigned FirstIntegralType = 0;
3253 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003254 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003255 LastPromotedIntegralType = 13;
3256 const unsigned FirstPromotedArithmeticType = 7,
3257 LastPromotedArithmeticType = 16;
3258 const unsigned NumArithmeticTypes = 16;
3259 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003260 Context.BoolTy, Context.CharTy, Context.WCharTy,
3261// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003262 Context.SignedCharTy, Context.ShortTy,
3263 Context.UnsignedCharTy, Context.UnsignedShortTy,
3264 Context.IntTy, Context.LongTy, Context.LongLongTy,
3265 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3266 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3267 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003268 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3269 "Invalid first promoted integral type");
3270 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3271 == Context.UnsignedLongLongTy &&
3272 "Invalid last promoted integral type");
3273 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3274 "Invalid first promoted arithmetic type");
3275 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3276 == Context.LongDoubleTy &&
3277 "Invalid last promoted arithmetic type");
3278
Douglas Gregora11693b2008-11-12 17:17:38 +00003279 // Find all of the types that the arguments can convert to, but only
3280 // if the operator we're looking at has built-in operator candidates
3281 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003282 Qualifiers VisibleTypeConversionsQuals;
3283 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003284 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3285 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3286
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003287 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003288 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3289 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003290 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003291 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003292 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003293 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003294 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003295 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003296 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003297 true,
3298 (Op == OO_Exclaim ||
3299 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003300 Op == OO_PipePipe),
3301 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003302 }
3303
3304 bool isComparison = false;
3305 switch (Op) {
3306 case OO_None:
3307 case NUM_OVERLOADED_OPERATORS:
3308 assert(false && "Expected an overloaded operator");
3309 break;
3310
Douglas Gregord08452f2008-11-19 15:42:04 +00003311 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003312 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003313 goto UnaryStar;
3314 else
3315 goto BinaryStar;
3316 break;
3317
3318 case OO_Plus: // '+' is either unary or binary
3319 if (NumArgs == 1)
3320 goto UnaryPlus;
3321 else
3322 goto BinaryPlus;
3323 break;
3324
3325 case OO_Minus: // '-' is either unary or binary
3326 if (NumArgs == 1)
3327 goto UnaryMinus;
3328 else
3329 goto BinaryMinus;
3330 break;
3331
3332 case OO_Amp: // '&' is either unary or binary
3333 if (NumArgs == 1)
3334 goto UnaryAmp;
3335 else
3336 goto BinaryAmp;
3337
3338 case OO_PlusPlus:
3339 case OO_MinusMinus:
3340 // C++ [over.built]p3:
3341 //
3342 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3343 // is either volatile or empty, there exist candidate operator
3344 // functions of the form
3345 //
3346 // VQ T& operator++(VQ T&);
3347 // T operator++(VQ T&, int);
3348 //
3349 // C++ [over.built]p4:
3350 //
3351 // For every pair (T, VQ), where T is an arithmetic type other
3352 // than bool, and VQ is either volatile or empty, there exist
3353 // candidate operator functions of the form
3354 //
3355 // VQ T& operator--(VQ T&);
3356 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003357 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003358 Arith < NumArithmeticTypes; ++Arith) {
3359 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003360 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003361 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003362
3363 // Non-volatile version.
3364 if (NumArgs == 1)
3365 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3366 else
3367 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003368 // heuristic to reduce number of builtin candidates in the set.
3369 // Add volatile version only if there are conversions to a volatile type.
3370 if (VisibleTypeConversionsQuals.hasVolatile()) {
3371 // Volatile version
3372 ParamTypes[0]
3373 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3374 if (NumArgs == 1)
3375 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3376 else
3377 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3378 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003379 }
3380
3381 // C++ [over.built]p5:
3382 //
3383 // For every pair (T, VQ), where T is a cv-qualified or
3384 // cv-unqualified object type, and VQ is either volatile or
3385 // empty, there exist candidate operator functions of the form
3386 //
3387 // T*VQ& operator++(T*VQ&);
3388 // T*VQ& operator--(T*VQ&);
3389 // T* operator++(T*VQ&, int);
3390 // T* operator--(T*VQ&, int);
3391 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3392 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3393 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003394 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003395 continue;
3396
Mike Stump11289f42009-09-09 15:08:12 +00003397 QualType ParamTypes[2] = {
3398 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003399 };
Mike Stump11289f42009-09-09 15:08:12 +00003400
Douglas Gregord08452f2008-11-19 15:42:04 +00003401 // Without volatile
3402 if (NumArgs == 1)
3403 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3404 else
3405 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3406
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003407 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3408 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003409 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003410 ParamTypes[0]
3411 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003412 if (NumArgs == 1)
3413 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3414 else
3415 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3416 }
3417 }
3418 break;
3419
3420 UnaryStar:
3421 // C++ [over.built]p6:
3422 // For every cv-qualified or cv-unqualified object type T, there
3423 // exist candidate operator functions of the form
3424 //
3425 // T& operator*(T*);
3426 //
3427 // C++ [over.built]p7:
3428 // For every function type T, there exist candidate operator
3429 // functions of the form
3430 // T& operator*(T*);
3431 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3432 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3433 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003434 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003435 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003436 &ParamTy, Args, 1, CandidateSet);
3437 }
3438 break;
3439
3440 UnaryPlus:
3441 // C++ [over.built]p8:
3442 // For every type T, there exist candidate operator functions of
3443 // the form
3444 //
3445 // T* operator+(T*);
3446 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3447 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3448 QualType ParamTy = *Ptr;
3449 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3450 }
Mike Stump11289f42009-09-09 15:08:12 +00003451
Douglas Gregord08452f2008-11-19 15:42:04 +00003452 // Fall through
3453
3454 UnaryMinus:
3455 // C++ [over.built]p9:
3456 // For every promoted arithmetic type T, there exist candidate
3457 // operator functions of the form
3458 //
3459 // T operator+(T);
3460 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003461 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003462 Arith < LastPromotedArithmeticType; ++Arith) {
3463 QualType ArithTy = ArithmeticTypes[Arith];
3464 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3465 }
3466 break;
3467
3468 case OO_Tilde:
3469 // C++ [over.built]p10:
3470 // For every promoted integral type T, there exist candidate
3471 // operator functions of the form
3472 //
3473 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003474 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003475 Int < LastPromotedIntegralType; ++Int) {
3476 QualType IntTy = ArithmeticTypes[Int];
3477 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3478 }
3479 break;
3480
Douglas Gregora11693b2008-11-12 17:17:38 +00003481 case OO_New:
3482 case OO_Delete:
3483 case OO_Array_New:
3484 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003485 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003486 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003487 break;
3488
3489 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003490 UnaryAmp:
3491 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003492 // C++ [over.match.oper]p3:
3493 // -- For the operator ',', the unary operator '&', or the
3494 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003495 break;
3496
Douglas Gregor84605ae2009-08-24 13:43:27 +00003497 case OO_EqualEqual:
3498 case OO_ExclaimEqual:
3499 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003500 // For every pointer to member type T, there exist candidate operator
3501 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003502 //
3503 // bool operator==(T,T);
3504 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003505 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003506 MemPtr = CandidateTypes.member_pointer_begin(),
3507 MemPtrEnd = CandidateTypes.member_pointer_end();
3508 MemPtr != MemPtrEnd;
3509 ++MemPtr) {
3510 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3511 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3512 }
Mike Stump11289f42009-09-09 15:08:12 +00003513
Douglas Gregor84605ae2009-08-24 13:43:27 +00003514 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003515
Douglas Gregora11693b2008-11-12 17:17:38 +00003516 case OO_Less:
3517 case OO_Greater:
3518 case OO_LessEqual:
3519 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003520 // C++ [over.built]p15:
3521 //
3522 // For every pointer or enumeration type T, there exist
3523 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003524 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003525 // bool operator<(T, T);
3526 // bool operator>(T, T);
3527 // bool operator<=(T, T);
3528 // bool operator>=(T, T);
3529 // bool operator==(T, T);
3530 // bool operator!=(T, T);
3531 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3532 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3533 QualType ParamTypes[2] = { *Ptr, *Ptr };
3534 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3535 }
Mike Stump11289f42009-09-09 15:08:12 +00003536 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003537 = CandidateTypes.enumeration_begin();
3538 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3539 QualType ParamTypes[2] = { *Enum, *Enum };
3540 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3541 }
3542
3543 // Fall through.
3544 isComparison = true;
3545
Douglas Gregord08452f2008-11-19 15:42:04 +00003546 BinaryPlus:
3547 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003548 if (!isComparison) {
3549 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3550
3551 // C++ [over.built]p13:
3552 //
3553 // For every cv-qualified or cv-unqualified object type T
3554 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003555 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003556 // T* operator+(T*, ptrdiff_t);
3557 // T& operator[](T*, ptrdiff_t); [BELOW]
3558 // T* operator-(T*, ptrdiff_t);
3559 // T* operator+(ptrdiff_t, T*);
3560 // T& operator[](ptrdiff_t, T*); [BELOW]
3561 //
3562 // C++ [over.built]p14:
3563 //
3564 // For every T, where T is a pointer to object type, there
3565 // exist candidate operator functions of the form
3566 //
3567 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003568 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003569 = CandidateTypes.pointer_begin();
3570 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3571 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3572
3573 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3574 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3575
3576 if (Op == OO_Plus) {
3577 // T* operator+(ptrdiff_t, T*);
3578 ParamTypes[0] = ParamTypes[1];
3579 ParamTypes[1] = *Ptr;
3580 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3581 } else {
3582 // ptrdiff_t operator-(T, T);
3583 ParamTypes[1] = *Ptr;
3584 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3585 Args, 2, CandidateSet);
3586 }
3587 }
3588 }
3589 // Fall through
3590
Douglas Gregora11693b2008-11-12 17:17:38 +00003591 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003592 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003593 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003594 // C++ [over.built]p12:
3595 //
3596 // For every pair of promoted arithmetic types L and R, there
3597 // exist candidate operator functions of the form
3598 //
3599 // LR operator*(L, R);
3600 // LR operator/(L, R);
3601 // LR operator+(L, R);
3602 // LR operator-(L, R);
3603 // bool operator<(L, R);
3604 // bool operator>(L, R);
3605 // bool operator<=(L, R);
3606 // bool operator>=(L, R);
3607 // bool operator==(L, R);
3608 // bool operator!=(L, R);
3609 //
3610 // where LR is the result of the usual arithmetic conversions
3611 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003612 //
3613 // C++ [over.built]p24:
3614 //
3615 // For every pair of promoted arithmetic types L and R, there exist
3616 // candidate operator functions of the form
3617 //
3618 // LR operator?(bool, L, R);
3619 //
3620 // where LR is the result of the usual arithmetic conversions
3621 // between types L and R.
3622 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003623 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003624 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003625 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003626 Right < LastPromotedArithmeticType; ++Right) {
3627 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003628 QualType Result
3629 = isComparison
3630 ? Context.BoolTy
3631 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003632 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3633 }
3634 }
3635 break;
3636
3637 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003638 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003639 case OO_Caret:
3640 case OO_Pipe:
3641 case OO_LessLess:
3642 case OO_GreaterGreater:
3643 // C++ [over.built]p17:
3644 //
3645 // For every pair of promoted integral types L and R, there
3646 // exist candidate operator functions of the form
3647 //
3648 // LR operator%(L, R);
3649 // LR operator&(L, R);
3650 // LR operator^(L, R);
3651 // LR operator|(L, R);
3652 // L operator<<(L, R);
3653 // L operator>>(L, R);
3654 //
3655 // where LR is the result of the usual arithmetic conversions
3656 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003657 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003658 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003659 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003660 Right < LastPromotedIntegralType; ++Right) {
3661 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3662 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3663 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003664 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003665 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3666 }
3667 }
3668 break;
3669
3670 case OO_Equal:
3671 // C++ [over.built]p20:
3672 //
3673 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003674 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003675 // empty, there exist candidate operator functions of the form
3676 //
3677 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003678 for (BuiltinCandidateTypeSet::iterator
3679 Enum = CandidateTypes.enumeration_begin(),
3680 EnumEnd = CandidateTypes.enumeration_end();
3681 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003682 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003683 CandidateSet);
3684 for (BuiltinCandidateTypeSet::iterator
3685 MemPtr = CandidateTypes.member_pointer_begin(),
3686 MemPtrEnd = CandidateTypes.member_pointer_end();
3687 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003688 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003689 CandidateSet);
3690 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003691
3692 case OO_PlusEqual:
3693 case OO_MinusEqual:
3694 // C++ [over.built]p19:
3695 //
3696 // For every pair (T, VQ), where T is any type and VQ is either
3697 // volatile or empty, there exist candidate operator functions
3698 // of the form
3699 //
3700 // T*VQ& operator=(T*VQ&, T*);
3701 //
3702 // C++ [over.built]p21:
3703 //
3704 // For every pair (T, VQ), where T is a cv-qualified or
3705 // cv-unqualified object type and VQ is either volatile or
3706 // empty, there exist candidate operator functions of the form
3707 //
3708 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3709 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3710 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3711 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3712 QualType ParamTypes[2];
3713 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3714
3715 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003716 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003717 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3718 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003719
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003720 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3721 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003722 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003723 ParamTypes[0]
3724 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003725 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3726 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003727 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003728 }
3729 // Fall through.
3730
3731 case OO_StarEqual:
3732 case OO_SlashEqual:
3733 // C++ [over.built]p18:
3734 //
3735 // For every triple (L, VQ, R), where L is an arithmetic type,
3736 // VQ is either volatile or empty, and R is a promoted
3737 // arithmetic type, there exist candidate operator functions of
3738 // the form
3739 //
3740 // VQ L& operator=(VQ L&, R);
3741 // VQ L& operator*=(VQ L&, R);
3742 // VQ L& operator/=(VQ L&, R);
3743 // VQ L& operator+=(VQ L&, R);
3744 // VQ L& operator-=(VQ L&, R);
3745 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003746 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003747 Right < LastPromotedArithmeticType; ++Right) {
3748 QualType ParamTypes[2];
3749 ParamTypes[1] = ArithmeticTypes[Right];
3750
3751 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003752 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003753 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3754 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003755
3756 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003757 if (VisibleTypeConversionsQuals.hasVolatile()) {
3758 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3759 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3760 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3761 /*IsAssigmentOperator=*/Op == OO_Equal);
3762 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003763 }
3764 }
3765 break;
3766
3767 case OO_PercentEqual:
3768 case OO_LessLessEqual:
3769 case OO_GreaterGreaterEqual:
3770 case OO_AmpEqual:
3771 case OO_CaretEqual:
3772 case OO_PipeEqual:
3773 // C++ [over.built]p22:
3774 //
3775 // For every triple (L, VQ, R), where L is an integral type, VQ
3776 // is either volatile or empty, and R is a promoted integral
3777 // type, there exist candidate operator functions of the form
3778 //
3779 // VQ L& operator%=(VQ L&, R);
3780 // VQ L& operator<<=(VQ L&, R);
3781 // VQ L& operator>>=(VQ L&, R);
3782 // VQ L& operator&=(VQ L&, R);
3783 // VQ L& operator^=(VQ L&, R);
3784 // VQ L& operator|=(VQ L&, R);
3785 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003786 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003787 Right < LastPromotedIntegralType; ++Right) {
3788 QualType ParamTypes[2];
3789 ParamTypes[1] = ArithmeticTypes[Right];
3790
3791 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003792 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003793 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00003794 if (VisibleTypeConversionsQuals.hasVolatile()) {
3795 // Add this built-in operator as a candidate (VQ is 'volatile').
3796 ParamTypes[0] = ArithmeticTypes[Left];
3797 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3798 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3799 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3800 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003801 }
3802 }
3803 break;
3804
Douglas Gregord08452f2008-11-19 15:42:04 +00003805 case OO_Exclaim: {
3806 // C++ [over.operator]p23:
3807 //
3808 // There also exist candidate operator functions of the form
3809 //
Mike Stump11289f42009-09-09 15:08:12 +00003810 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003811 // bool operator&&(bool, bool); [BELOW]
3812 // bool operator||(bool, bool); [BELOW]
3813 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003814 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3815 /*IsAssignmentOperator=*/false,
3816 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003817 break;
3818 }
3819
Douglas Gregora11693b2008-11-12 17:17:38 +00003820 case OO_AmpAmp:
3821 case OO_PipePipe: {
3822 // C++ [over.operator]p23:
3823 //
3824 // There also exist candidate operator functions of the form
3825 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003826 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003827 // bool operator&&(bool, bool);
3828 // bool operator||(bool, bool);
3829 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003830 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3831 /*IsAssignmentOperator=*/false,
3832 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003833 break;
3834 }
3835
3836 case OO_Subscript:
3837 // C++ [over.built]p13:
3838 //
3839 // For every cv-qualified or cv-unqualified object type T there
3840 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003841 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003842 // T* operator+(T*, ptrdiff_t); [ABOVE]
3843 // T& operator[](T*, ptrdiff_t);
3844 // T* operator-(T*, ptrdiff_t); [ABOVE]
3845 // T* operator+(ptrdiff_t, T*); [ABOVE]
3846 // T& operator[](ptrdiff_t, T*);
3847 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3848 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3849 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003850 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003851 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003852
3853 // T& operator[](T*, ptrdiff_t)
3854 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3855
3856 // T& operator[](ptrdiff_t, T*);
3857 ParamTypes[0] = ParamTypes[1];
3858 ParamTypes[1] = *Ptr;
3859 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3860 }
3861 break;
3862
3863 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003864 // C++ [over.built]p11:
3865 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3866 // C1 is the same type as C2 or is a derived class of C2, T is an object
3867 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3868 // there exist candidate operator functions of the form
3869 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3870 // where CV12 is the union of CV1 and CV2.
3871 {
3872 for (BuiltinCandidateTypeSet::iterator Ptr =
3873 CandidateTypes.pointer_begin();
3874 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3875 QualType C1Ty = (*Ptr);
3876 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003877 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003878 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003879 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003880 if (!isa<RecordType>(C1))
3881 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003882 // heuristic to reduce number of builtin candidates in the set.
3883 // Add volatile/restrict version only if there are conversions to a
3884 // volatile/restrict type.
3885 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3886 continue;
3887 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3888 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003889 }
3890 for (BuiltinCandidateTypeSet::iterator
3891 MemPtr = CandidateTypes.member_pointer_begin(),
3892 MemPtrEnd = CandidateTypes.member_pointer_end();
3893 MemPtr != MemPtrEnd; ++MemPtr) {
3894 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3895 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00003896 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003897 if (C1 != C2 && !IsDerivedFrom(C1, C2))
3898 break;
3899 QualType ParamTypes[2] = { *Ptr, *MemPtr };
3900 // build CV12 T&
3901 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003902 if (!VisibleTypeConversionsQuals.hasVolatile() &&
3903 T.isVolatileQualified())
3904 continue;
3905 if (!VisibleTypeConversionsQuals.hasRestrict() &&
3906 T.isRestrictQualified())
3907 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003908 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003909 QualType ResultTy = Context.getLValueReferenceType(T);
3910 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3911 }
3912 }
3913 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003914 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003915
3916 case OO_Conditional:
3917 // Note that we don't consider the first argument, since it has been
3918 // contextually converted to bool long ago. The candidates below are
3919 // therefore added as binary.
3920 //
3921 // C++ [over.built]p24:
3922 // For every type T, where T is a pointer or pointer-to-member type,
3923 // there exist candidate operator functions of the form
3924 //
3925 // T operator?(bool, T, T);
3926 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00003927 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3928 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3929 QualType ParamTypes[2] = { *Ptr, *Ptr };
3930 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3931 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003932 for (BuiltinCandidateTypeSet::iterator Ptr =
3933 CandidateTypes.member_pointer_begin(),
3934 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3935 QualType ParamTypes[2] = { *Ptr, *Ptr };
3936 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3937 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003938 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00003939 }
3940}
3941
Douglas Gregore254f902009-02-04 00:32:51 +00003942/// \brief Add function candidates found via argument-dependent lookup
3943/// to the set of overloading candidates.
3944///
3945/// This routine performs argument-dependent name lookup based on the
3946/// given function name (which may also be an operator name) and adds
3947/// all of the overload candidates found by ADL to the overload
3948/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00003949void
Douglas Gregore254f902009-02-04 00:32:51 +00003950Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3951 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00003952 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00003953 OverloadCandidateSet& CandidateSet,
3954 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003955 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00003956
Douglas Gregorcabea402009-09-22 15:41:20 +00003957 // FIXME: Should we be trafficking in canonical function decls throughout?
3958
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003959 // Record all of the function candidates that we've already
3960 // added to the overload set, so that we don't add those same
3961 // candidates a second time.
3962 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3963 CandEnd = CandidateSet.end();
3964 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003965 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003966 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003967 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3968 Functions.insert(FunTmpl);
3969 }
Douglas Gregore254f902009-02-04 00:32:51 +00003970
Douglas Gregorcabea402009-09-22 15:41:20 +00003971 // FIXME: Pass in the explicit template arguments?
Sebastian Redlc057f422009-10-23 19:23:15 +00003972 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00003973
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003974 // Erase all of the candidates we already knew about.
3975 // FIXME: This is suboptimal. Is there a better way?
3976 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3977 CandEnd = CandidateSet.end();
3978 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003979 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003980 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003981 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3982 Functions.erase(FunTmpl);
3983 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003984
3985 // For each of the ADL candidates we found, add it to the overload
3986 // set.
3987 for (FunctionSet::iterator Func = Functions.begin(),
3988 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00003989 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003990 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
John McCall6b51f282009-11-23 01:53:49 +00003991 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00003992 continue;
3993
3994 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
3995 false, false, PartialOverloading);
3996 } else
Mike Stump11289f42009-09-09 15:08:12 +00003997 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00003998 ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003999 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004000 }
Douglas Gregore254f902009-02-04 00:32:51 +00004001}
4002
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004003/// isBetterOverloadCandidate - Determines whether the first overload
4004/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004005bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004006Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00004007 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004008 // Define viable functions to be better candidates than non-viable
4009 // functions.
4010 if (!Cand2.Viable)
4011 return Cand1.Viable;
4012 else if (!Cand1.Viable)
4013 return false;
4014
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004015 // C++ [over.match.best]p1:
4016 //
4017 // -- if F is a static member function, ICS1(F) is defined such
4018 // that ICS1(F) is neither better nor worse than ICS1(G) for
4019 // any function G, and, symmetrically, ICS1(G) is neither
4020 // better nor worse than ICS1(F).
4021 unsigned StartArg = 0;
4022 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4023 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004024
Douglas Gregord3cb3562009-07-07 23:38:56 +00004025 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004026 // A viable function F1 is defined to be a better function than another
4027 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004028 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004029 unsigned NumArgs = Cand1.Conversions.size();
4030 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4031 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004032 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004033 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4034 Cand2.Conversions[ArgIdx])) {
4035 case ImplicitConversionSequence::Better:
4036 // Cand1 has a better conversion sequence.
4037 HasBetterConversion = true;
4038 break;
4039
4040 case ImplicitConversionSequence::Worse:
4041 // Cand1 can't be better than Cand2.
4042 return false;
4043
4044 case ImplicitConversionSequence::Indistinguishable:
4045 // Do nothing.
4046 break;
4047 }
4048 }
4049
Mike Stump11289f42009-09-09 15:08:12 +00004050 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004051 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004052 if (HasBetterConversion)
4053 return true;
4054
Mike Stump11289f42009-09-09 15:08:12 +00004055 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004056 // specialization, or, if not that,
4057 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4058 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4059 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004060
4061 // -- F1 and F2 are function template specializations, and the function
4062 // template for F1 is more specialized than the template for F2
4063 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004064 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004065 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4066 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004067 if (FunctionTemplateDecl *BetterTemplate
4068 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4069 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00004070 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4071 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004072 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004073
Douglas Gregora1f013e2008-11-07 22:36:19 +00004074 // -- the context is an initialization by user-defined conversion
4075 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4076 // from the return type of F1 to the destination type (i.e.,
4077 // the type of the entity being initialized) is a better
4078 // conversion sequence than the standard conversion sequence
4079 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004080 if (Cand1.Function && Cand2.Function &&
4081 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004082 isa<CXXConversionDecl>(Cand2.Function)) {
4083 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4084 Cand2.FinalConversion)) {
4085 case ImplicitConversionSequence::Better:
4086 // Cand1 has a better conversion sequence.
4087 return true;
4088
4089 case ImplicitConversionSequence::Worse:
4090 // Cand1 can't be better than Cand2.
4091 return false;
4092
4093 case ImplicitConversionSequence::Indistinguishable:
4094 // Do nothing
4095 break;
4096 }
4097 }
4098
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004099 return false;
4100}
4101
Mike Stump11289f42009-09-09 15:08:12 +00004102/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004103/// within an overload candidate set.
4104///
4105/// \param CandidateSet the set of candidate functions.
4106///
4107/// \param Loc the location of the function name (or operator symbol) for
4108/// which overload resolution occurs.
4109///
Mike Stump11289f42009-09-09 15:08:12 +00004110/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004111/// function, Best points to the candidate function found.
4112///
4113/// \returns The result of overload resolution.
Mike Stump11289f42009-09-09 15:08:12 +00004114Sema::OverloadingResult
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004115Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004116 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004117 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004118 // Find the best viable function.
4119 Best = CandidateSet.end();
4120 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4121 Cand != CandidateSet.end(); ++Cand) {
4122 if (Cand->Viable) {
4123 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4124 Best = Cand;
4125 }
4126 }
4127
4128 // If we didn't find any viable functions, abort.
4129 if (Best == CandidateSet.end())
4130 return OR_No_Viable_Function;
4131
4132 // Make sure that this function is better than every other viable
4133 // function. If not, we have an ambiguity.
4134 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4135 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004136 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004137 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00004138 !isBetterOverloadCandidate(*Best, *Cand)) {
4139 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004140 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004141 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004142 }
Mike Stump11289f42009-09-09 15:08:12 +00004143
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004144 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004145 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004146 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004147 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004148 return OR_Deleted;
4149
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004150 // C++ [basic.def.odr]p2:
4151 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004152 // when referred to from a potentially-evaluated expression. [Note: this
4153 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004154 // (clause 13), user-defined conversions (12.3.2), allocation function for
4155 // placement new (5.3.4), as well as non-default initialization (8.5).
4156 if (Best->Function)
4157 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004158 return OR_Success;
4159}
4160
4161/// PrintOverloadCandidates - When overload resolution fails, prints
4162/// diagnostic messages containing the candidates in the candidate
4163/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump11289f42009-09-09 15:08:12 +00004164void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004165Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004166 bool OnlyViable,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004167 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004168 SourceLocation OpLoc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004169 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4170 LastCand = CandidateSet.end();
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004171 bool Reported = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004172 for (; Cand != LastCand; ++Cand) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004173 if (Cand->Viable || !OnlyViable) {
4174 if (Cand->Function) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004175 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004176 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004177 // Deleted or "unavailable" function.
4178 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4179 << Cand->Function->isDeleted();
Douglas Gregor4fb9cde8e2009-09-15 20:11:42 +00004180 } else if (FunctionTemplateDecl *FunTmpl
4181 = Cand->Function->getPrimaryTemplate()) {
4182 // Function template specialization
4183 // FIXME: Give a better reason!
4184 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4185 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4186 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor171c45a2009-02-18 21:56:37 +00004187 } else {
4188 // Normal function
Fariborz Jahanian21ccf062009-09-23 00:58:07 +00004189 bool errReported = false;
4190 if (!Cand->Viable && Cand->Conversions.size() > 0) {
4191 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4192 const ImplicitConversionSequence &Conversion =
4193 Cand->Conversions[i];
4194 if ((Conversion.ConversionKind !=
4195 ImplicitConversionSequence::BadConversion) ||
4196 Conversion.ConversionFunctionSet.size() == 0)
4197 continue;
4198 Diag(Cand->Function->getLocation(),
4199 diag::err_ovl_candidate_not_viable) << (i+1);
4200 errReported = true;
4201 for (int j = Conversion.ConversionFunctionSet.size()-1;
4202 j >= 0; j--) {
4203 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4204 Diag(Func->getLocation(), diag::err_ovl_candidate);
4205 }
4206 }
4207 }
4208 if (!errReported)
4209 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor171c45a2009-02-18 21:56:37 +00004210 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00004211 } else if (Cand->IsSurrogate) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004212 // Desugar the type of the surrogate down to a function type,
4213 // retaining as many typedefs as possible while still showing
4214 // the function type (and, therefore, its parameter types).
4215 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004216 bool isLValueReference = false;
4217 bool isRValueReference = false;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004218 bool isPointer = false;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004219 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004220 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004221 FnType = FnTypeRef->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004222 isLValueReference = true;
4223 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004224 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004225 FnType = FnTypeRef->getPointeeType();
4226 isRValueReference = true;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004227 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004228 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004229 FnType = FnTypePtr->getPointeeType();
4230 isPointer = true;
4231 }
4232 // Desugar down to a function type.
John McCall9dd450b2009-09-21 23:43:11 +00004233 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004234 // Reconstruct the pointer/reference as appropriate.
4235 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004236 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4237 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004238
Douglas Gregorab7897a2008-11-19 22:57:39 +00004239 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004240 << FnType;
Douglas Gregor66950a32009-09-30 21:46:01 +00004241 } else if (OnlyViable) {
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004242 assert(Cand->Conversions.size() <= 2 &&
Fariborz Jahanian0fe5e032009-10-09 17:09:58 +00004243 "builtin-binary-operator-not-binary");
Fariborz Jahanian956127d2009-10-16 23:25:02 +00004244 std::string TypeStr("operator");
4245 TypeStr += Opc;
4246 TypeStr += "(";
4247 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4248 if (Cand->Conversions.size() == 1) {
4249 TypeStr += ")";
4250 Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr;
4251 }
4252 else {
4253 TypeStr += ", ";
4254 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4255 TypeStr += ")";
4256 Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr;
4257 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004258 }
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004259 else if (!Cand->Viable && !Reported) {
4260 // Non-viability might be due to ambiguous user-defined conversions,
4261 // needed for built-in operators. Report them as well, but only once
4262 // as we have typically many built-in candidates.
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004263 unsigned NoOperands = Cand->Conversions.size();
4264 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004265 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4266 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4267 ICS.ConversionFunctionSet.empty())
4268 continue;
4269 if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4270 Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4271 QualType FromTy =
4272 QualType(
4273 static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4274 Diag(OpLoc,diag::note_ambiguous_type_conversion)
4275 << FromTy << Func->getConversionType();
4276 }
4277 for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4278 FunctionDecl *Func =
4279 Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4280 Diag(Func->getLocation(),diag::err_ovl_candidate);
4281 }
4282 }
4283 Reported = true;
4284 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004285 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004286 }
4287}
4288
Douglas Gregorcd695e52008-11-10 20:40:00 +00004289/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4290/// an overloaded function (C++ [over.over]), where @p From is an
4291/// expression with overloaded function type and @p ToType is the type
4292/// we're trying to resolve to. For example:
4293///
4294/// @code
4295/// int f(double);
4296/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004297///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004298/// int (*pfd)(double) = f; // selects f(double)
4299/// @endcode
4300///
4301/// This routine returns the resulting FunctionDecl if it could be
4302/// resolved, and NULL otherwise. When @p Complain is true, this
4303/// routine will emit diagnostics if there is an error.
4304FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004305Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004306 bool Complain) {
4307 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004308 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004309 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004310 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004311 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004312 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004313 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004314 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004315 FunctionType = MemTypePtr->getPointeeType();
4316 IsMember = true;
4317 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004318
4319 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00004320 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00004321 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004322 return 0;
4323
4324 // Find the actual overloaded function declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004325
Douglas Gregorcd695e52008-11-10 20:40:00 +00004326 // C++ [over.over]p1:
4327 // [...] [Note: any redundant set of parentheses surrounding the
4328 // overloaded function name is ignored (5.1). ]
4329 Expr *OvlExpr = From->IgnoreParens();
4330
4331 // C++ [over.over]p1:
4332 // [...] The overloaded function name can be preceded by the &
4333 // operator.
4334 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4335 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4336 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4337 }
4338
Anders Carlssonb68b0282009-10-20 22:53:47 +00004339 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004340 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCalld14a8642009-11-21 08:51:07 +00004341
4342 llvm::SmallVector<NamedDecl*,8> Fns;
Anders Carlssonb68b0282009-10-20 22:53:47 +00004343
John McCall10eae182009-11-30 22:42:35 +00004344 // Look into the overloaded expression.
John McCalle66edc12009-11-24 19:00:30 +00004345 if (UnresolvedLookupExpr *UL
John McCalld14a8642009-11-21 08:51:07 +00004346 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4347 Fns.append(UL->decls_begin(), UL->decls_end());
John McCalle66edc12009-11-24 19:00:30 +00004348 if (UL->hasExplicitTemplateArgs()) {
4349 HasExplicitTemplateArgs = true;
4350 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4351 }
John McCall10eae182009-11-30 22:42:35 +00004352 } else if (UnresolvedMemberExpr *ME
4353 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4354 Fns.append(ME->decls_begin(), ME->decls_end());
4355 if (ME->hasExplicitTemplateArgs()) {
4356 HasExplicitTemplateArgs = true;
John McCall6b51f282009-11-23 01:53:49 +00004357 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004358 }
Douglas Gregor9b146582009-07-08 20:55:45 +00004359 }
Mike Stump11289f42009-09-09 15:08:12 +00004360
John McCalld14a8642009-11-21 08:51:07 +00004361 // If we didn't actually find anything, we're done.
4362 if (Fns.empty())
4363 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004364
Douglas Gregorcd695e52008-11-10 20:40:00 +00004365 // Look through all of the overloaded functions, searching for one
4366 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004367 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004368 bool FoundNonTemplateFunction = false;
John McCalld14a8642009-11-21 08:51:07 +00004369 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4370 E = Fns.end(); I != E; ++I) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004371 // C++ [over.over]p3:
4372 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00004373 // targets of type "pointer-to-function" or "reference-to-function."
4374 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004375 // type "pointer-to-member-function."
4376 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004377
Mike Stump11289f42009-09-09 15:08:12 +00004378 if (FunctionTemplateDecl *FunctionTemplate
John McCalld14a8642009-11-21 08:51:07 +00004379 = dyn_cast<FunctionTemplateDecl>(*I)) {
Mike Stump11289f42009-09-09 15:08:12 +00004380 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004381 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004382 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004383 // static when converting to member pointer.
4384 if (Method->isStatic() == IsMember)
4385 continue;
4386 } else if (IsMember)
4387 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004388
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004389 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004390 // If the name is a function template, template argument deduction is
4391 // done (14.8.2.2), and if the argument deduction succeeds, the
4392 // resulting template argument list is used to generate a single
4393 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004394 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004395 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00004396 FunctionDecl *Specialization = 0;
4397 TemplateDeductionInfo Info(Context);
4398 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004399 = DeduceTemplateArguments(FunctionTemplate,
4400 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
Douglas Gregor9b146582009-07-08 20:55:45 +00004401 FunctionType, Specialization, Info)) {
4402 // FIXME: make a note of the failed deduction for diagnostics.
4403 (void)Result;
4404 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004405 // FIXME: If the match isn't exact, shouldn't we just drop this as
4406 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00004407 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004408 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004409 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004410 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004411 }
John McCalld14a8642009-11-21 08:51:07 +00004412
4413 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00004414 }
Mike Stump11289f42009-09-09 15:08:12 +00004415
John McCalld14a8642009-11-21 08:51:07 +00004416 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004417 // Skip non-static functions when converting to pointer, and static
4418 // when converting to member pointer.
4419 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004420 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00004421
4422 // If we have explicit template arguments, skip non-templates.
4423 if (HasExplicitTemplateArgs)
4424 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004425 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004426 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004427
John McCalld14a8642009-11-21 08:51:07 +00004428 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*I)) {
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004429 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
John McCalld14a8642009-11-21 08:51:07 +00004430 Matches.insert(cast<FunctionDecl>(FunDecl->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004431 FoundNonTemplateFunction = true;
4432 }
Mike Stump11289f42009-09-09 15:08:12 +00004433 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004434 }
4435
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004436 // If there were 0 or 1 matches, we're done.
4437 if (Matches.empty())
4438 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004439 else if (Matches.size() == 1) {
4440 FunctionDecl *Result = *Matches.begin();
4441 MarkDeclarationReferenced(From->getLocStart(), Result);
4442 return Result;
4443 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004444
4445 // C++ [over.over]p4:
4446 // If more than one function is selected, [...]
Douglas Gregor05155d82009-08-21 23:19:43 +00004447 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorfae1d712009-09-26 03:56:17 +00004448 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004449 // [...] and any given function template specialization F1 is
4450 // eliminated if the set contains a second function template
4451 // specialization whose function template is more specialized
4452 // than the function template of F1 according to the partial
4453 // ordering rules of 14.5.5.2.
4454
4455 // The algorithm specified above is quadratic. We instead use a
4456 // two-pass algorithm (similar to the one used to identify the
4457 // best viable function in an overload set) that identifies the
4458 // best function template (if it exists).
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004459 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregorfae1d712009-09-26 03:56:17 +00004460 Matches.end());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004461 FunctionDecl *Result =
4462 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4463 TPOC_Other, From->getLocStart(),
4464 PDiag(),
4465 PDiag(diag::err_addr_ovl_ambiguous)
4466 << TemplateMatches[0]->getDeclName(),
4467 PDiag(diag::err_ovl_template_candidate));
4468 MarkDeclarationReferenced(From->getLocStart(), Result);
4469 return Result;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004470 }
Mike Stump11289f42009-09-09 15:08:12 +00004471
Douglas Gregorfae1d712009-09-26 03:56:17 +00004472 // [...] any function template specializations in the set are
4473 // eliminated if the set also contains a non-template function, [...]
4474 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4475 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4476 if ((*M)->getPrimaryTemplate() == 0)
4477 RemainingMatches.push_back(*M);
4478
Mike Stump11289f42009-09-09 15:08:12 +00004479 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004480 // selected function.
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004481 if (RemainingMatches.size() == 1) {
4482 FunctionDecl *Result = RemainingMatches.front();
4483 MarkDeclarationReferenced(From->getLocStart(), Result);
4484 return Result;
4485 }
Mike Stump11289f42009-09-09 15:08:12 +00004486
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004487 // FIXME: We should probably return the same thing that BestViableFunction
4488 // returns (even if we issue the diagnostics here).
4489 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4490 << RemainingMatches[0]->getDeclName();
4491 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4492 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004493 return 0;
4494}
4495
Douglas Gregorcabea402009-09-22 15:41:20 +00004496/// \brief Add a single candidate to the overload set.
4497static void AddOverloadedCallCandidate(Sema &S,
John McCalld14a8642009-11-21 08:51:07 +00004498 NamedDecl *Callee,
John McCall6b51f282009-11-23 01:53:49 +00004499 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004500 Expr **Args, unsigned NumArgs,
4501 OverloadCandidateSet &CandidateSet,
4502 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00004503 if (isa<UsingShadowDecl>(Callee))
4504 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
4505
Douglas Gregorcabea402009-09-22 15:41:20 +00004506 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00004507 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregorcabea402009-09-22 15:41:20 +00004508 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4509 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004510 return;
John McCalld14a8642009-11-21 08:51:07 +00004511 }
4512
4513 if (FunctionTemplateDecl *FuncTemplate
4514 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00004515 S.AddTemplateOverloadCandidate(FuncTemplate, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00004516 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00004517 return;
4518 }
4519
4520 assert(false && "unhandled case in overloaded call candidate");
4521
4522 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00004523}
4524
4525/// \brief Add the overload candidates named by callee and/or found by argument
4526/// dependent lookup to the given overload set.
John McCalld14a8642009-11-21 08:51:07 +00004527void Sema::AddOverloadedCallCandidates(llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregorcabea402009-09-22 15:41:20 +00004528 DeclarationName &UnqualifiedName,
John McCall4b1f16e2009-11-21 09:38:42 +00004529 bool ArgumentDependentLookup,
John McCall6b51f282009-11-23 01:53:49 +00004530 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004531 Expr **Args, unsigned NumArgs,
4532 OverloadCandidateSet &CandidateSet,
4533 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00004534
4535#ifndef NDEBUG
4536 // Verify that ArgumentDependentLookup is consistent with the rules
4537 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00004538 //
Douglas Gregorcabea402009-09-22 15:41:20 +00004539 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4540 // and let Y be the lookup set produced by argument dependent
4541 // lookup (defined as follows). If X contains
4542 //
4543 // -- a declaration of a class member, or
4544 //
4545 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00004546 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00004547 //
4548 // -- a declaration that is neither a function or a function
4549 // template
4550 //
4551 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00004552
4553 if (ArgumentDependentLookup) {
4554 for (unsigned I = 0; I < Fns.size(); ++I) {
4555 assert(!Fns[I]->getDeclContext()->isRecord());
4556 assert(isa<UsingShadowDecl>(Fns[I]) ||
4557 !Fns[I]->getDeclContext()->isFunctionOrMethod());
4558 assert(Fns[I]->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
4559 }
4560 }
4561#endif
4562
4563 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4564 E = Fns.end(); I != E; ++I)
John McCall6b51f282009-11-23 01:53:49 +00004565 AddOverloadedCallCandidate(*this, *I, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00004566 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00004567 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00004568
Douglas Gregorcabea402009-09-22 15:41:20 +00004569 if (ArgumentDependentLookup)
4570 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004571 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004572 CandidateSet,
4573 PartialOverloading);
4574}
4575
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004576/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00004577/// (which eventually refers to the declaration Func) and the call
4578/// arguments Args/NumArgs, attempt to resolve the function call down
4579/// to a specific function. If overload resolution succeeds, returns
4580/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00004581/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004582/// arguments and Fn, and returns NULL.
John McCalld14a8642009-11-21 08:51:07 +00004583FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn,
4584 llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004585 DeclarationName UnqualifiedName,
John McCall6b51f282009-11-23 01:53:49 +00004586 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregora60a6912008-11-26 06:01:48 +00004587 SourceLocation LParenLoc,
4588 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004589 SourceLocation *CommaLocs,
Douglas Gregore254f902009-02-04 00:32:51 +00004590 SourceLocation RParenLoc,
John McCall4b1f16e2009-11-21 09:38:42 +00004591 bool ArgumentDependentLookup) {
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004592 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004593
4594 // Add the functions denoted by Callee to the set of candidate
Douglas Gregorcabea402009-09-22 15:41:20 +00004595 // functions.
John McCalld14a8642009-11-21 08:51:07 +00004596 AddOverloadedCallCandidates(Fns, UnqualifiedName, ArgumentDependentLookup,
John McCall6b51f282009-11-23 01:53:49 +00004597 ExplicitTemplateArgs, Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004598 CandidateSet);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004599 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004600 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregora60a6912008-11-26 06:01:48 +00004601 case OR_Success:
4602 return Best->Function;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004603
4604 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00004605 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004606 diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004607 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004608 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4609 break;
4610
4611 case OR_Ambiguous:
4612 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004613 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004614 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4615 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004616
4617 case OR_Deleted:
4618 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4619 << Best->Function->isDeleted()
4620 << UnqualifiedName
4621 << Fn->getSourceRange();
4622 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4623 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004624 }
4625
4626 // Overload resolution failed. Destroy all of the subexpressions and
4627 // return NULL.
4628 Fn->Destroy(Context);
4629 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4630 Args[Arg]->Destroy(Context);
4631 return 0;
4632}
4633
John McCall283b9012009-11-22 00:44:51 +00004634static bool IsOverloaded(const Sema::FunctionSet &Functions) {
4635 return Functions.size() > 1 ||
4636 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
4637}
4638
Douglas Gregor084d8552009-03-13 23:49:33 +00004639/// \brief Create a unary operation that may resolve to an overloaded
4640/// operator.
4641///
4642/// \param OpLoc The location of the operator itself (e.g., '*').
4643///
4644/// \param OpcIn The UnaryOperator::Opcode that describes this
4645/// operator.
4646///
4647/// \param Functions The set of non-member functions that will be
4648/// considered by overload resolution. The caller needs to build this
4649/// set based on the context using, e.g.,
4650/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4651/// set should not contain any member functions; those will be added
4652/// by CreateOverloadedUnaryOp().
4653///
4654/// \param input The input argument.
4655Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4656 unsigned OpcIn,
4657 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00004658 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004659 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4660 Expr *Input = (Expr *)input.get();
4661
4662 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4663 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4664 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4665
4666 Expr *Args[2] = { Input, 0 };
4667 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004668
Douglas Gregor084d8552009-03-13 23:49:33 +00004669 // For post-increment and post-decrement, add the implicit '0' as
4670 // the second argument, so that we know this is a post-increment or
4671 // post-decrement.
4672 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4673 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00004674 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00004675 SourceLocation());
4676 NumArgs = 2;
4677 }
4678
4679 if (Input->isTypeDependent()) {
John McCalld14a8642009-11-21 08:51:07 +00004680 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00004681 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
4682 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00004683 /*ADL*/ true, IsOverloaded(Functions));
Mike Stump11289f42009-09-09 15:08:12 +00004684 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00004685 FuncEnd = Functions.end();
4686 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00004687 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00004688
Douglas Gregor084d8552009-03-13 23:49:33 +00004689 input.release();
4690 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4691 &Args[0], NumArgs,
4692 Context.DependentTy,
4693 OpLoc));
4694 }
4695
4696 // Build an empty overload set.
4697 OverloadCandidateSet CandidateSet;
4698
4699 // Add the candidates from the given function set.
4700 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4701
4702 // Add operator candidates that are member functions.
4703 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4704
4705 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004706 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00004707
4708 // Perform overload resolution.
4709 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004710 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004711 case OR_Success: {
4712 // We found a built-in operator or an overloaded operator.
4713 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00004714
Douglas Gregor084d8552009-03-13 23:49:33 +00004715 if (FnDecl) {
4716 // We matched an overloaded operator. Build a call to that
4717 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00004718
Douglas Gregor084d8552009-03-13 23:49:33 +00004719 // Convert the arguments.
4720 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4721 if (PerformObjectArgumentInitialization(Input, Method))
4722 return ExprError();
4723 } else {
4724 // Convert the arguments.
4725 if (PerformCopyInitialization(Input,
4726 FnDecl->getParamDecl(0)->getType(),
4727 "passing"))
4728 return ExprError();
4729 }
4730
4731 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004732 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004733
Douglas Gregor084d8552009-03-13 23:49:33 +00004734 // Build the actual expression node.
4735 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4736 SourceLocation());
4737 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004738
Douglas Gregor084d8552009-03-13 23:49:33 +00004739 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00004740 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004741 ExprOwningPtr<CallExpr> TheCall(this,
4742 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00004743 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004744
4745 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4746 FnDecl))
4747 return ExprError();
4748
4749 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00004750 } else {
4751 // We matched a built-in operator. Convert the arguments, then
4752 // break out so that we will build the appropriate built-in
4753 // operator node.
4754 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4755 Best->Conversions[0], "passing"))
4756 return ExprError();
4757
4758 break;
4759 }
4760 }
4761
4762 case OR_No_Viable_Function:
4763 // No viable function; fall through to handling this as a
4764 // built-in operator, which will produce an error message for us.
4765 break;
4766
4767 case OR_Ambiguous:
4768 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4769 << UnaryOperator::getOpcodeStr(Opc)
4770 << Input->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004771 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4772 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00004773 return ExprError();
4774
4775 case OR_Deleted:
4776 Diag(OpLoc, diag::err_ovl_deleted_oper)
4777 << Best->Function->isDeleted()
4778 << UnaryOperator::getOpcodeStr(Opc)
4779 << Input->getSourceRange();
4780 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4781 return ExprError();
4782 }
4783
4784 // Either we found no viable overloaded operator or we matched a
4785 // built-in operator. In either case, fall through to trying to
4786 // build a built-in operation.
4787 input.release();
4788 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4789}
4790
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004791/// \brief Create a binary operation that may resolve to an overloaded
4792/// operator.
4793///
4794/// \param OpLoc The location of the operator itself (e.g., '+').
4795///
4796/// \param OpcIn The BinaryOperator::Opcode that describes this
4797/// operator.
4798///
4799/// \param Functions The set of non-member functions that will be
4800/// considered by overload resolution. The caller needs to build this
4801/// set based on the context using, e.g.,
4802/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4803/// set should not contain any member functions; those will be added
4804/// by CreateOverloadedBinOp().
4805///
4806/// \param LHS Left-hand argument.
4807/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00004808Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004809Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004810 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004811 FunctionSet &Functions,
4812 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004813 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00004814 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004815
4816 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4817 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4818 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4819
4820 // If either side is type-dependent, create an appropriate dependent
4821 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00004822 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00004823 if (Functions.empty()) {
4824 // If there are no functions to store, just build a dependent
4825 // BinaryOperator or CompoundAssignment.
4826 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
4827 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
4828 Context.DependentTy, OpLoc));
4829
4830 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
4831 Context.DependentTy,
4832 Context.DependentTy,
4833 Context.DependentTy,
4834 OpLoc));
4835 }
4836
John McCalld14a8642009-11-21 08:51:07 +00004837 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00004838 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
4839 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00004840 /* ADL */ true, IsOverloaded(Functions));
John McCalld14a8642009-11-21 08:51:07 +00004841
Mike Stump11289f42009-09-09 15:08:12 +00004842 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004843 FuncEnd = Functions.end();
4844 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00004845 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00004846
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004847 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00004848 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004849 Context.DependentTy,
4850 OpLoc));
4851 }
4852
4853 // If this is the .* operator, which is not overloadable, just
4854 // create a built-in binary operator.
4855 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004856 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004857
Sebastian Redl6a96bf72009-11-18 23:10:33 +00004858 // If this is the assignment operator, we only perform overload resolution
4859 // if the left-hand side is a class or enumeration type. This is actually
4860 // a hack. The standard requires that we do overload resolution between the
4861 // various built-in candidates, but as DR507 points out, this can lead to
4862 // problems. So we do it this way, which pretty much follows what GCC does.
4863 // Note that we go the traditional code path for compound assignment forms.
4864 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00004865 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004866
Douglas Gregor084d8552009-03-13 23:49:33 +00004867 // Build an empty overload set.
4868 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004869
4870 // Add the candidates from the given function set.
4871 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4872
4873 // Add operator candidates that are member functions.
4874 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4875
4876 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004877 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004878
4879 // Perform overload resolution.
4880 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004881 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004882 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004883 // We found a built-in operator or an overloaded operator.
4884 FunctionDecl *FnDecl = Best->Function;
4885
4886 if (FnDecl) {
4887 // We matched an overloaded operator. Build a call to that
4888 // operator.
4889
4890 // Convert the arguments.
4891 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregore9899d92009-08-26 17:08:25 +00004892 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4893 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004894 "passing"))
4895 return ExprError();
4896 } else {
4897 // Convert the arguments.
Douglas Gregore9899d92009-08-26 17:08:25 +00004898 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004899 "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004900 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004901 "passing"))
4902 return ExprError();
4903 }
4904
4905 // Determine the result type
4906 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00004907 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004908 ResultTy = ResultTy.getNonReferenceType();
4909
4910 // Build the actual expression node.
4911 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00004912 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004913 UsualUnaryConversions(FnExpr);
4914
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00004915 ExprOwningPtr<CXXOperatorCallExpr>
4916 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4917 Args, 2, ResultTy,
4918 OpLoc));
4919
4920 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4921 FnDecl))
4922 return ExprError();
4923
4924 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004925 } else {
4926 // We matched a built-in operator. Convert the arguments, then
4927 // break out so that we will build the appropriate built-in
4928 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00004929 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004930 Best->Conversions[0], "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004931 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004932 Best->Conversions[1], "passing"))
4933 return ExprError();
4934
4935 break;
4936 }
4937 }
4938
Douglas Gregor66950a32009-09-30 21:46:01 +00004939 case OR_No_Viable_Function: {
4940 // C++ [over.match.oper]p9:
4941 // If the operator is the operator , [...] and there are no
4942 // viable functions, then the operator is assumed to be the
4943 // built-in operator and interpreted according to clause 5.
4944 if (Opc == BinaryOperator::Comma)
4945 break;
4946
Sebastian Redl027de2a2009-05-21 11:50:50 +00004947 // For class as left operand for assignment or compound assigment operator
4948 // do not fall through to handling in built-in, but report that no overloaded
4949 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00004950 OwningExprResult Result = ExprError();
4951 if (Args[0]->getType()->isRecordType() &&
4952 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00004953 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4954 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004955 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00004956 } else {
4957 // No viable function; try to create a built-in operation, which will
4958 // produce an error. Then, show the non-viable candidates.
4959 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00004960 }
Douglas Gregor66950a32009-09-30 21:46:01 +00004961 assert(Result.isInvalid() &&
4962 "C++ binary operator overloading is missing candidates!");
4963 if (Result.isInvalid())
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004964 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
4965 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00004966 return move(Result);
4967 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004968
4969 case OR_Ambiguous:
4970 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4971 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004972 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004973 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4974 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004975 return ExprError();
4976
4977 case OR_Deleted:
4978 Diag(OpLoc, diag::err_ovl_deleted_oper)
4979 << Best->Function->isDeleted()
4980 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004981 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004982 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4983 return ExprError();
4984 }
4985
Douglas Gregor66950a32009-09-30 21:46:01 +00004986 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00004987 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004988}
4989
Sebastian Redladba46e2009-10-29 20:17:01 +00004990Action::OwningExprResult
4991Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
4992 SourceLocation RLoc,
4993 ExprArg Base, ExprArg Idx) {
4994 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
4995 static_cast<Expr*>(Idx.get()) };
4996 DeclarationName OpName =
4997 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
4998
4999 // If either side is type-dependent, create an appropriate dependent
5000 // expression.
5001 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5002
John McCalld14a8642009-11-21 08:51:07 +00005003 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005004 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5005 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00005006 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00005007 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00005008
5009 Base.release();
5010 Idx.release();
5011 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5012 Args, 2,
5013 Context.DependentTy,
5014 RLoc));
5015 }
5016
5017 // Build an empty overload set.
5018 OverloadCandidateSet CandidateSet;
5019
5020 // Subscript can only be overloaded as a member function.
5021
5022 // Add operator candidates that are member functions.
5023 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5024
5025 // Add builtin operator candidates.
5026 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5027
5028 // Perform overload resolution.
5029 OverloadCandidateSet::iterator Best;
5030 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5031 case OR_Success: {
5032 // We found a built-in operator or an overloaded operator.
5033 FunctionDecl *FnDecl = Best->Function;
5034
5035 if (FnDecl) {
5036 // We matched an overloaded operator. Build a call to that
5037 // operator.
5038
5039 // Convert the arguments.
5040 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5041 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5042 PerformCopyInitialization(Args[1],
5043 FnDecl->getParamDecl(0)->getType(),
5044 "passing"))
5045 return ExprError();
5046
5047 // Determine the result type
5048 QualType ResultTy
5049 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5050 ResultTy = ResultTy.getNonReferenceType();
5051
5052 // Build the actual expression node.
5053 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5054 LLoc);
5055 UsualUnaryConversions(FnExpr);
5056
5057 Base.release();
5058 Idx.release();
5059 ExprOwningPtr<CXXOperatorCallExpr>
5060 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5061 FnExpr, Args, 2,
5062 ResultTy, RLoc));
5063
5064 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5065 FnDecl))
5066 return ExprError();
5067
5068 return MaybeBindToTemporary(TheCall.release());
5069 } else {
5070 // We matched a built-in operator. Convert the arguments, then
5071 // break out so that we will build the appropriate built-in
5072 // operator node.
5073 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
5074 Best->Conversions[0], "passing") ||
5075 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
5076 Best->Conversions[1], "passing"))
5077 return ExprError();
5078
5079 break;
5080 }
5081 }
5082
5083 case OR_No_Viable_Function: {
5084 // No viable function; try to create a built-in operation, which will
5085 // produce an error. Then, show the non-viable candidates.
5086 OwningExprResult Result =
5087 CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
5088 assert(Result.isInvalid() &&
5089 "C++ subscript operator overloading is missing candidates!");
5090 if (Result.isInvalid())
5091 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5092 "[]", LLoc);
5093 return move(Result);
5094 }
5095
5096 case OR_Ambiguous:
5097 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5098 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5099 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5100 "[]", LLoc);
5101 return ExprError();
5102
5103 case OR_Deleted:
5104 Diag(LLoc, diag::err_ovl_deleted_oper)
5105 << Best->Function->isDeleted() << "[]"
5106 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5107 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5108 return ExprError();
5109 }
5110
5111 // We matched a built-in operator; build it.
5112 Base.release();
5113 Idx.release();
5114 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5115 Owned(Args[1]), RLoc);
5116}
5117
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005118/// BuildCallToMemberFunction - Build a call to a member
5119/// function. MemExpr is the expression that refers to the member
5120/// function (and includes the object parameter), Args/NumArgs are the
5121/// arguments to the function call (not including the object
5122/// parameter). The caller needs to validate that the member
5123/// expression refers to a member function or an overloaded member
5124/// function.
5125Sema::ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00005126Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5127 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005128 unsigned NumArgs, SourceLocation *CommaLocs,
5129 SourceLocation RParenLoc) {
5130 // Dig out the member expression. This holds both the object
5131 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00005132 Expr *NakedMemExpr = MemExprE->IgnoreParens();
5133
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005134 // Extract the object argument.
John McCall10eae182009-11-30 22:42:35 +00005135 Expr *ObjectArg;
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005136
John McCall10eae182009-11-30 22:42:35 +00005137 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005138 CXXMethodDecl *Method = 0;
John McCall10eae182009-11-30 22:42:35 +00005139 if (isa<MemberExpr>(NakedMemExpr)) {
5140 MemExpr = cast<MemberExpr>(NakedMemExpr);
5141 ObjectArg = MemExpr->getBase();
5142 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5143 } else {
5144 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
5145 ObjectArg = UnresExpr->getBase();
5146
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005147 // Add overload candidates
5148 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00005149
John McCall10eae182009-11-30 22:42:35 +00005150 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
5151 E = UnresExpr->decls_end(); I != E; ++I) {
5152
5153 // TODO: note if we found something through a using declaration
5154 NamedDecl *Func = (*I)->getUnderlyingDecl();
5155
5156 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00005157 // If explicit template arguments were provided, we can't call a
5158 // non-template member function.
John McCall10eae182009-11-30 22:42:35 +00005159 if (UnresExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00005160 continue;
5161
Mike Stump11289f42009-09-09 15:08:12 +00005162 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005163 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005164 } else {
5165 // FIXME: avoid copy.
5166 TemplateArgumentListInfo TemplateArgs;
John McCall10eae182009-11-30 22:42:35 +00005167 if (UnresExpr->hasExplicitTemplateArgs())
5168 UnresExpr->copyTemplateArgumentsInto(TemplateArgs);
John McCall6b51f282009-11-23 01:53:49 +00005169
John McCall10eae182009-11-30 22:42:35 +00005170 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
5171 (UnresExpr->hasExplicitTemplateArgs()
John McCall6b51f282009-11-23 01:53:49 +00005172 ? &TemplateArgs : 0),
Douglas Gregor84f14dd2009-09-01 00:37:14 +00005173 ObjectArg, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005174 CandidateSet,
5175 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005176 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005177 }
Mike Stump11289f42009-09-09 15:08:12 +00005178
John McCall10eae182009-11-30 22:42:35 +00005179 DeclarationName DeclName = UnresExpr->getMemberName();
5180
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005181 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00005182 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005183 case OR_Success:
5184 Method = cast<CXXMethodDecl>(Best->Function);
5185 break;
5186
5187 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00005188 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005189 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005190 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005191 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5192 // FIXME: Leaking incoming expressions!
5193 return true;
5194
5195 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00005196 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005197 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005198 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5199 // FIXME: Leaking incoming expressions!
5200 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005201
5202 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00005203 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00005204 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00005205 << DeclName << MemExprE->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005206 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5207 // FIXME: Leaking incoming expressions!
5208 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005209 }
5210
Douglas Gregor51c538b2009-11-20 19:42:02 +00005211 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCall10eae182009-11-30 22:42:35 +00005212 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005213 }
5214
5215 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00005216 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005217 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
Mike Stump11289f42009-09-09 15:08:12 +00005218 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005219 Method->getResultType().getNonReferenceType(),
5220 RParenLoc));
5221
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005222 // Check for a valid return type.
5223 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5224 TheCall.get(), Method))
5225 return true;
5226
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005227 // Convert the object argument (for a non-static member function call).
Mike Stump11289f42009-09-09 15:08:12 +00005228 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005229 PerformObjectArgumentInitialization(ObjectArg, Method))
5230 return true;
5231 MemExpr->setBase(ObjectArg);
5232
5233 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005234 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00005235 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005236 RParenLoc))
5237 return true;
5238
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005239 if (CheckFunctionCall(Method, TheCall.get()))
5240 return true;
Anders Carlsson8c84c202009-08-16 03:42:12 +00005241
5242 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005243}
5244
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005245/// BuildCallToObjectOfClassType - Build a call to an object of class
5246/// type (C++ [over.call.object]), which can end up invoking an
5247/// overloaded function call operator (@c operator()) or performing a
5248/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00005249Sema::ExprResult
5250Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00005251 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005252 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00005253 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005254 SourceLocation RParenLoc) {
5255 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005256 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00005257
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005258 // C++ [over.call.object]p1:
5259 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00005260 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005261 // candidate functions includes at least the function call
5262 // operators of T. The function call operators of T are obtained by
5263 // ordinary lookup of the name operator() in the context of
5264 // (E).operator().
5265 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00005266 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005267
5268 if (RequireCompleteType(LParenLoc, Object->getType(),
5269 PartialDiagnostic(diag::err_incomplete_object_call)
5270 << Object->getSourceRange()))
5271 return true;
5272
John McCall27b18f82009-11-17 02:14:36 +00005273 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5274 LookupQualifiedName(R, Record->getDecl());
5275 R.suppressDiagnostics();
5276
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005277 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00005278 Oper != OperEnd; ++Oper) {
John McCallf0f1cf02009-11-17 07:50:12 +00005279 AddMethodCandidate(*Oper, Object, Args, NumArgs, CandidateSet,
5280 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00005281 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005282
Douglas Gregorab7897a2008-11-19 22:57:39 +00005283 // C++ [over.call.object]p2:
5284 // In addition, for each conversion function declared in T of the
5285 // form
5286 //
5287 // operator conversion-type-id () cv-qualifier;
5288 //
5289 // where cv-qualifier is the same cv-qualification as, or a
5290 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00005291 // denotes the type "pointer to function of (P1,...,Pn) returning
5292 // R", or the type "reference to pointer to function of
5293 // (P1,...,Pn) returning R", or the type "reference to function
5294 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00005295 // is also considered as a candidate function. Similarly,
5296 // surrogate call functions are added to the set of candidate
5297 // functions for each conversion function declared in an
5298 // accessible base class provided the function is not hidden
5299 // within T by another intervening declaration.
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005300 // FIXME: Look in base classes for more conversion operators!
John McCalld14a8642009-11-21 08:51:07 +00005301 const UnresolvedSet *Conversions
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005302 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00005303 for (UnresolvedSet::iterator I = Conversions->begin(),
5304 E = Conversions->end(); I != E; ++I) {
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005305 // Skip over templated conversion functions; they aren't
5306 // surrogates.
John McCalld14a8642009-11-21 08:51:07 +00005307 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005308 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005309
John McCalld14a8642009-11-21 08:51:07 +00005310 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
5311
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005312 // Strip the reference type (if any) and then the pointer type (if
5313 // any) to get down to what might be a function type.
5314 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5315 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5316 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005317
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005318 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
5319 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00005320 }
Mike Stump11289f42009-09-09 15:08:12 +00005321
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005322 // Perform overload resolution.
5323 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005324 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005325 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00005326 // Overload resolution succeeded; we'll build the appropriate call
5327 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005328 break;
5329
5330 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00005331 Diag(Object->getSourceRange().getBegin(),
Sebastian Redl15b02d22008-11-22 13:44:36 +00005332 diag::err_ovl_no_viable_object_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00005333 << Object->getType() << Object->getSourceRange();
Sebastian Redl15b02d22008-11-22 13:44:36 +00005334 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005335 break;
5336
5337 case OR_Ambiguous:
5338 Diag(Object->getSourceRange().getBegin(),
5339 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005340 << Object->getType() << Object->getSourceRange();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005341 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5342 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005343
5344 case OR_Deleted:
5345 Diag(Object->getSourceRange().getBegin(),
5346 diag::err_ovl_deleted_object_call)
5347 << Best->Function->isDeleted()
5348 << Object->getType() << Object->getSourceRange();
5349 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5350 break;
Mike Stump11289f42009-09-09 15:08:12 +00005351 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005352
Douglas Gregorab7897a2008-11-19 22:57:39 +00005353 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005354 // We had an error; delete all of the subexpressions and return
5355 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00005356 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005357 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00005358 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005359 return true;
5360 }
5361
Douglas Gregorab7897a2008-11-19 22:57:39 +00005362 if (Best->Function == 0) {
5363 // Since there is no function declaration, this is one of the
5364 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00005365 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00005366 = cast<CXXConversionDecl>(
5367 Best->Conversions[0].UserDefined.ConversionFunction);
5368
5369 // We selected one of the surrogate functions that converts the
5370 // object parameter to a function pointer. Perform the conversion
5371 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005372
5373 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005374 // and then call it.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005375 CXXMemberCallExpr *CE =
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005376 BuildCXXMemberCallExpr(Object, Conv);
5377
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005378 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005379 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5380 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005381 }
5382
5383 // We found an overloaded operator(). Build a CXXOperatorCallExpr
5384 // that calls this method, using Object for the implicit object
5385 // parameter and passing along the remaining arguments.
5386 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00005387 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005388
5389 unsigned NumArgsInProto = Proto->getNumArgs();
5390 unsigned NumArgsToCheck = NumArgs;
5391
5392 // Build the full argument list for the method call (the
5393 // implicit object parameter is placed at the beginning of the
5394 // list).
5395 Expr **MethodArgs;
5396 if (NumArgs < NumArgsInProto) {
5397 NumArgsToCheck = NumArgsInProto;
5398 MethodArgs = new Expr*[NumArgsInProto + 1];
5399 } else {
5400 MethodArgs = new Expr*[NumArgs + 1];
5401 }
5402 MethodArgs[0] = Object;
5403 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5404 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00005405
5406 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00005407 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005408 UsualUnaryConversions(NewFn);
5409
5410 // Once we've built TheCall, all of the expressions are properly
5411 // owned.
5412 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005413 ExprOwningPtr<CXXOperatorCallExpr>
5414 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005415 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00005416 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005417 delete [] MethodArgs;
5418
Anders Carlsson3d5829c2009-10-13 21:49:31 +00005419 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5420 Method))
5421 return true;
5422
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005423 // We may have default arguments. If so, we need to allocate more
5424 // slots in the call for them.
5425 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00005426 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005427 else if (NumArgs > NumArgsInProto)
5428 NumArgsToCheck = NumArgsInProto;
5429
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005430 bool IsError = false;
5431
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005432 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005433 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005434 TheCall->setArg(0, Object);
5435
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005436
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005437 // Check the argument types.
5438 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005439 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005440 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005441 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00005442
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005443 // Pass the argument.
5444 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005445 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005446 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00005447 OwningExprResult DefArg
5448 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
5449 if (DefArg.isInvalid()) {
5450 IsError = true;
5451 break;
5452 }
5453
5454 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005455 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005456
5457 TheCall->setArg(i + 1, Arg);
5458 }
5459
5460 // If this is a variadic call, handle args passed through "...".
5461 if (Proto->isVariadic()) {
5462 // Promote the arguments (C99 6.5.2.2p7).
5463 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5464 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005465 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005466 TheCall->setArg(i + 1, Arg);
5467 }
5468 }
5469
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005470 if (IsError) return true;
5471
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005472 if (CheckFunctionCall(Method, TheCall.get()))
5473 return true;
5474
Anders Carlsson1c83deb2009-08-16 03:53:54 +00005475 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005476}
5477
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005478/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00005479/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005480/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00005481Sema::OwningExprResult
5482Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5483 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005484 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00005485
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005486 // C++ [over.ref]p1:
5487 //
5488 // [...] An expression x->m is interpreted as (x.operator->())->m
5489 // for a class object x of type T if T::operator->() exists and if
5490 // the operator is selected as the best match function by the
5491 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005492 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5493 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005494 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00005495
Eli Friedman132e70b2009-11-18 01:28:03 +00005496 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
5497 PDiag(diag::err_typecheck_incomplete_tag)
5498 << Base->getSourceRange()))
5499 return ExprError();
5500
John McCall27b18f82009-11-17 02:14:36 +00005501 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
5502 LookupQualifiedName(R, BaseRecord->getDecl());
5503 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00005504
5505 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
5506 Oper != OperEnd; ++Oper)
Douglas Gregor55297ac2008-12-23 00:26:44 +00005507 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005508 /*SuppressUserConversions=*/false);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005509
5510 // Perform overload resolution.
5511 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005512 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005513 case OR_Success:
5514 // Overload resolution succeeded; we'll build the call below.
5515 break;
5516
5517 case OR_No_Viable_Function:
5518 if (CandidateSet.empty())
5519 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00005520 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005521 else
5522 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00005523 << "operator->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005524 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregord8061562009-08-06 03:17:00 +00005525 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005526
5527 case OR_Ambiguous:
5528 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00005529 << "->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005530 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005531 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005532
5533 case OR_Deleted:
5534 Diag(OpLoc, diag::err_ovl_deleted_oper)
5535 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00005536 << "->" << Base->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005537 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005538 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005539 }
5540
5541 // Convert the object parameter.
5542 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00005543 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00005544 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00005545
5546 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00005547 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005548
5549 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00005550 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5551 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005552 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005553
5554 QualType ResultTy = Method->getResultType().getNonReferenceType();
5555 ExprOwningPtr<CXXOperatorCallExpr>
5556 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
5557 &Base, 1, ResultTy, OpLoc));
5558
5559 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
5560 Method))
5561 return ExprError();
5562 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005563}
5564
Douglas Gregorcd695e52008-11-10 20:40:00 +00005565/// FixOverloadedFunctionReference - E is an expression that refers to
5566/// a C++ overloaded function (possibly with some parentheses and
5567/// perhaps a '&' around it). We have resolved the overloaded function
5568/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005569/// refer (possibly indirectly) to Fn. Returns the new expr.
5570Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005571 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor51c538b2009-11-20 19:42:02 +00005572 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5573 if (SubExpr == PE->getSubExpr())
5574 return PE->Retain();
5575
5576 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
5577 }
5578
5579 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5580 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00005581 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00005582 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00005583 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00005584 if (SubExpr == ICE->getSubExpr())
5585 return ICE->Retain();
5586
5587 return new (Context) ImplicitCastExpr(ICE->getType(),
5588 ICE->getCastKind(),
5589 SubExpr,
5590 ICE->isLvalueCast());
5591 }
5592
5593 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00005594 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00005595 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005596 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5597 if (Method->isStatic()) {
5598 // Do nothing: static member functions aren't any different
5599 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00005600 } else {
John McCalle66edc12009-11-24 19:00:30 +00005601 // Fix the sub expression, which really has to be an
5602 // UnresolvedLookupExpr holding an overloaded member function
5603 // or template.
John McCalld14a8642009-11-21 08:51:07 +00005604 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5605 if (SubExpr == UnOp->getSubExpr())
5606 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00005607
John McCalld14a8642009-11-21 08:51:07 +00005608 assert(isa<DeclRefExpr>(SubExpr)
5609 && "fixed to something other than a decl ref");
5610 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
5611 && "fixed to a member ref with no nested name qualifier");
5612
5613 // We have taken the address of a pointer to member
5614 // function. Perform the computation here so that we get the
5615 // appropriate pointer to member type.
5616 QualType ClassType
5617 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5618 QualType MemPtrType
5619 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
5620
5621 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5622 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005623 }
5624 }
Douglas Gregor51c538b2009-11-20 19:42:02 +00005625 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5626 if (SubExpr == UnOp->getSubExpr())
5627 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005628
Douglas Gregor51c538b2009-11-20 19:42:02 +00005629 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5630 Context.getPointerType(SubExpr->getType()),
5631 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00005632 }
John McCalld14a8642009-11-21 08:51:07 +00005633
5634 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCalle66edc12009-11-24 19:00:30 +00005635 if (ULE->hasExplicitTemplateArgs()) {
5636 // FIXME: avoid copy.
5637 TemplateArgumentListInfo TemplateArgs;
5638 if (ULE->hasExplicitTemplateArgs())
5639 ULE->copyTemplateArgumentsInto(TemplateArgs);
5640
5641 return DeclRefExpr::Create(Context,
5642 ULE->getQualifier(),
5643 ULE->getQualifierRange(),
5644 Fn,
5645 ULE->getNameLoc(),
5646 Fn->getType(),
5647 &TemplateArgs);
5648 }
5649
John McCalld14a8642009-11-21 08:51:07 +00005650 return DeclRefExpr::Create(Context,
5651 ULE->getQualifier(),
5652 ULE->getQualifierRange(),
5653 Fn,
5654 ULE->getNameLoc(),
Douglas Gregored6c7442009-11-23 11:41:28 +00005655 Fn->getType());
John McCalld14a8642009-11-21 08:51:07 +00005656 }
5657
John McCall10eae182009-11-30 22:42:35 +00005658 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00005659 // FIXME: avoid copy.
5660 TemplateArgumentListInfo TemplateArgs;
John McCall10eae182009-11-30 22:42:35 +00005661 if (MemExpr->hasExplicitTemplateArgs())
John McCall6b51f282009-11-23 01:53:49 +00005662 MemExpr->copyTemplateArgumentsInto(TemplateArgs);
5663
Douglas Gregor51c538b2009-11-20 19:42:02 +00005664 return MemberExpr::Create(Context, MemExpr->getBase()->Retain(),
5665 MemExpr->isArrow(),
5666 MemExpr->getQualifier(),
5667 MemExpr->getQualifierRange(),
5668 Fn,
John McCall6b51f282009-11-23 01:53:49 +00005669 MemExpr->getMemberLoc(),
John McCall10eae182009-11-30 22:42:35 +00005670 (MemExpr->hasExplicitTemplateArgs()
John McCall6b51f282009-11-23 01:53:49 +00005671 ? &TemplateArgs : 0),
Douglas Gregor51c538b2009-11-20 19:42:02 +00005672 Fn->getType());
5673 }
5674
Douglas Gregor51c538b2009-11-20 19:42:02 +00005675 assert(false && "Invalid reference to overloaded function");
5676 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00005677}
5678
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005679} // end namespace clang