blob: 2c8c7317975e7e6ebf85154e13a631a486421793 [file] [log] [blame]
Douglas Gregord2baafd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregorbb461502008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregor70d26122008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregor10f3c502008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregor70d26122008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Anders Carlssona21e7872009-08-26 23:45:07 +000022#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor3d4492e2008-11-13 20:12:29 +000023#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000025#include "llvm/Support/Compiler.h"
26#include <algorithm>
Edwin Török0fbc71c2009-08-24 13:25:12 +000027#include <cstdio>
Douglas Gregord2baafd2008-10-21 16:13:35 +000028
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
33ImplicitConversionCategory
34GetConversionCategory(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 Gregore819caf2009-02-12 00:15:05 +000044 ICC_Promotion,
45 ICC_Conversion,
46 ICC_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000047 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000052 ICC_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000053 ICC_Conversion,
Douglas Gregord2baafd2008-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 Gregore819caf2009-02-12 00:15:05 +000071 ICR_Promotion,
72 ICR_Conversion,
73 ICR_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000074 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000079 ICR_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000080 ICR_Conversion,
Douglas Gregord2baafd2008-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 Gregore819caf2009-02-12 00:15:05 +000097 "Complex promotion",
Douglas Gregord2baafd2008-10-21 16:13:35 +000098 "Integral conversion",
99 "Floating conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +0000100 "Complex conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +0000101 "Floating-integral conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +0000102 "Complex-real conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +0000103 "Pointer conversion",
104 "Pointer-to-member conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000105 "Boolean conversion",
Douglas Gregorfcb19192009-02-11 23:02:49 +0000106 "Compatible-types conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000107 "Derived-to-base conversion"
Douglas Gregord2baafd2008-10-21 16:13:35 +0000108 };
109 return Name[Kind];
110}
111
Douglas Gregorb72e9da2008-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 Redl9bc16ad2009-03-29 22:46:24 +0000121 RRefBinding = false;
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000122 CopyConstructor = 0;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000123}
124
Douglas Gregord2baafd2008-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
141/// used as part of the ranking of standard conversion sequences
142/// (C++ 13.3.3.2p4).
143bool StandardConversionSequence::isPointerConversionToBool() const
144{
145 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
146 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
147
148 // Note that FromType has not necessarily been transformed by the
149 // array-to-pointer or function-to-pointer implicit conversions, so
150 // check for their presence as well as checking whether FromType is
151 // a pointer.
152 if (ToType->isBooleanType() &&
Douglas Gregor80402cf2008-12-23 00:53:59 +0000153 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregord2baafd2008-10-21 16:13:35 +0000154 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
155 return true;
156
157 return false;
158}
159
Douglas Gregor14046502008-10-23 00:40:37 +0000160/// isPointerConversionToVoidPointer - Determines whether this
161/// conversion is a conversion of a pointer to a void pointer. This is
162/// used as part of the ranking of standard conversion sequences (C++
163/// 13.3.3.2p4).
164bool
165StandardConversionSequence::
166isPointerConversionToVoidPointer(ASTContext& Context) const
167{
168 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
169 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
170
171 // Note that FromType has not necessarily been transformed by the
172 // array-to-pointer implicit conversion, so check for its presence
173 // and redo the conversion to get a pointer.
174 if (First == ICK_Array_To_Pointer)
175 FromType = Context.getArrayDecayedType(FromType);
176
177 if (Second == ICK_Pointer_Conversion)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000178 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor14046502008-10-23 00:40:37 +0000179 return ToPtrType->getPointeeType()->isVoidType();
180
181 return false;
182}
183
Douglas Gregord2baafd2008-10-21 16:13:35 +0000184/// DebugPrint - Print this standard conversion sequence to standard
185/// error. Useful for debugging overloading issues.
186void StandardConversionSequence::DebugPrint() const {
187 bool PrintedSomething = false;
188 if (First != ICK_Identity) {
189 fprintf(stderr, "%s", GetImplicitConversionName(First));
190 PrintedSomething = true;
191 }
192
193 if (Second != ICK_Identity) {
194 if (PrintedSomething) {
195 fprintf(stderr, " -> ");
196 }
197 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000198
199 if (CopyConstructor) {
200 fprintf(stderr, " (by copy constructor)");
201 } else if (DirectBinding) {
202 fprintf(stderr, " (direct reference binding)");
203 } else if (ReferenceBinding) {
204 fprintf(stderr, " (reference binding)");
205 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000206 PrintedSomething = true;
207 }
208
209 if (Third != ICK_Identity) {
210 if (PrintedSomething) {
211 fprintf(stderr, " -> ");
212 }
213 fprintf(stderr, "%s", GetImplicitConversionName(Third));
214 PrintedSomething = true;
215 }
216
217 if (!PrintedSomething) {
218 fprintf(stderr, "No conversions required");
219 }
220}
221
222/// DebugPrint - Print this user-defined conversion sequence to standard
223/// error. Useful for debugging overloading issues.
224void UserDefinedConversionSequence::DebugPrint() const {
225 if (Before.First || Before.Second || Before.Third) {
226 Before.DebugPrint();
227 fprintf(stderr, " -> ");
228 }
Chris Lattner271d4c22008-11-24 05:29:24 +0000229 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregord2baafd2008-10-21 16:13:35 +0000230 if (After.First || After.Second || After.Third) {
231 fprintf(stderr, " -> ");
232 After.DebugPrint();
233 }
234}
235
236/// DebugPrint - Print this implicit conversion sequence to standard
237/// error. Useful for debugging overloading issues.
238void ImplicitConversionSequence::DebugPrint() const {
239 switch (ConversionKind) {
240 case StandardConversion:
241 fprintf(stderr, "Standard conversion: ");
242 Standard.DebugPrint();
243 break;
244 case UserDefinedConversion:
245 fprintf(stderr, "User-defined conversion: ");
246 UserDefined.DebugPrint();
247 break;
248 case EllipsisConversion:
249 fprintf(stderr, "Ellipsis conversion");
250 break;
251 case BadConversion:
252 fprintf(stderr, "Bad conversion");
253 break;
254 }
255
256 fprintf(stderr, "\n");
257}
258
259// IsOverload - Determine whether the given New declaration is an
260// overload of the Old declaration. This routine returns false if New
261// and Old cannot be overloaded, e.g., if they are functions with the
262// same signature (C++ 1.3.10) or if the Old declaration isn't a
263// function (or overload set). When it does return false and Old is an
264// OverloadedFunctionDecl, MatchedDecl will be set to point to the
265// FunctionDecl that New cannot be overloaded with.
266//
267// Example: Given the following input:
268//
269// void f(int, float); // #1
270// void f(int, int); // #2
271// int f(int, int); // #3
272//
273// When we process #1, there is no previous declaration of "f",
274// so IsOverload will not be used.
275//
276// When we process #2, Old is a FunctionDecl for #1. By comparing the
277// parameter types, we see that #1 and #2 are overloaded (since they
278// have different signatures), so this routine returns false;
279// MatchedDecl is unchanged.
280//
281// When we process #3, Old is an OverloadedFunctionDecl containing #1
282// and #2. We compare the signatures of #3 to #1 (they're overloaded,
283// so we do nothing) and then #3 to #2. Since the signatures of #3 and
284// #2 are identical (return types of functions are not part of the
285// signature), IsOverload returns false and MatchedDecl will be set to
286// point to the FunctionDecl for #2.
287bool
288Sema::IsOverload(FunctionDecl *New, Decl* OldD,
289 OverloadedFunctionDecl::function_iterator& MatchedDecl)
290{
291 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
292 // Is this new function an overload of every function in the
293 // overload set?
294 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
295 FuncEnd = Ovl->function_end();
296 for (; Func != FuncEnd; ++Func) {
297 if (!IsOverload(New, *Func, MatchedDecl)) {
298 MatchedDecl = Func;
299 return false;
300 }
301 }
302
303 // This function overloads every function in the overload set.
304 return true;
Douglas Gregorb60eb752009-06-25 22:08:12 +0000305 } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
306 return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
307 else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000308 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
309 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
310
311 // C++ [temp.fct]p2:
312 // A function template can be overloaded with other function templates
313 // and with normal (non-template) functions.
314 if ((OldTemplate == 0) != (NewTemplate == 0))
315 return true;
316
Douglas Gregord2baafd2008-10-21 16:13:35 +0000317 // Is the function New an overload of the function Old?
318 QualType OldQType = Context.getCanonicalType(Old->getType());
319 QualType NewQType = Context.getCanonicalType(New->getType());
320
321 // Compare the signatures (C++ 1.3.10) of the two functions to
322 // determine whether they are overloads. If we find any mismatch
323 // in the signature, they are overloads.
324
325 // If either of these functions is a K&R-style function (no
326 // prototype), then we consider them to have matching signatures.
Douglas Gregor4fa58902009-02-26 23:50:07 +0000327 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
328 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregord2baafd2008-10-21 16:13:35 +0000329 return false;
330
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000331 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
332 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000333
334 // The signature of a function includes the types of its
335 // parameters (C++ 1.3.10), which includes the presence or absence
336 // of the ellipsis; see C++ DR 357).
337 if (OldQType != NewQType &&
338 (OldType->getNumArgs() != NewType->getNumArgs() ||
339 OldType->isVariadic() != NewType->isVariadic() ||
340 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
341 NewType->arg_type_begin())))
342 return true;
343
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000344 // C++ [temp.over.link]p4:
345 // The signature of a function template consists of its function
346 // signature, its return type and its template parameter list. The names
347 // of the template parameters are significant only for establishing the
348 // relationship between the template parameters and the rest of the
349 // signature.
350 //
351 // We check the return type and template parameter lists for function
352 // templates first; the remaining checks follow.
353 if (NewTemplate &&
354 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
355 OldTemplate->getTemplateParameters(),
356 false, false, SourceLocation()) ||
357 OldType->getResultType() != NewType->getResultType()))
358 return true;
359
Douglas Gregord2baafd2008-10-21 16:13:35 +0000360 // If the function is a class member, its signature includes the
361 // cv-qualifiers (if any) on the function itself.
362 //
363 // As part of this, also check whether one of the member functions
364 // is static, in which case they are not overloads (C++
365 // 13.1p2). While not part of the definition of the signature,
366 // this check is important to determine whether these functions
367 // can be overloaded.
368 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
369 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
370 if (OldMethod && NewMethod &&
371 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregora7b56a32008-11-21 15:36:28 +0000372 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregord2baafd2008-10-21 16:13:35 +0000373 return true;
374
375 // The signatures match; this is not an overload.
376 return false;
377 } else {
378 // (C++ 13p1):
379 // Only function declarations can be overloaded; object and type
380 // declarations cannot be overloaded.
381 return false;
382 }
383}
384
Douglas Gregor81c29152008-10-29 00:13:59 +0000385/// TryImplicitConversion - Attempt to perform an implicit conversion
386/// from the given expression (Expr) to the given type (ToType). This
387/// function returns an implicit conversion sequence that can be used
388/// to perform the initialization. Given
Douglas Gregord2baafd2008-10-21 16:13:35 +0000389///
390/// void f(float f);
391/// void g(int i) { f(i); }
392///
393/// this routine would produce an implicit conversion sequence to
394/// describe the initialization of f from i, which will be a standard
395/// conversion sequence containing an lvalue-to-rvalue conversion (C++
396/// 4.1) followed by a floating-integral conversion (C++ 4.9).
397//
398/// Note that this routine only determines how the conversion can be
399/// performed; it does not actually perform the conversion. As such,
400/// it will not produce any diagnostics if no conversion is available,
401/// but will instead return an implicit conversion sequence of kind
402/// "BadConversion".
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000403///
404/// If @p SuppressUserConversions, then user-defined conversions are
405/// not permitted.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000406/// If @p AllowExplicit, then explicit user-defined conversions are
407/// permitted.
Sebastian Redla55834a2009-04-12 17:16:29 +0000408/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
409/// no matter its actual lvalueness.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000410ImplicitConversionSequence
Anders Carlssonf4a65092009-08-27 16:01:18 +0000411Sema::TryImplicitConversion(Expr* From, QualType ToType, unsigned Flags) {
412 bool SuppressUserConversions = Flags & ORF_SuppressUserConversions;
413 bool AllowExplicit = Flags & ORF_AllowExplicit;
414 bool ForceRValue = Flags & ORF_ForceRValue;
415
Douglas Gregord2baafd2008-10-21 16:13:35 +0000416 ImplicitConversionSequence ICS;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000417 if (IsStandardConversion(From, ToType, ICS.Standard))
418 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000419 else if (getLangOptions().CPlusPlus &&
420 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Sebastian Redla55834a2009-04-12 17:16:29 +0000421 !SuppressUserConversions, AllowExplicit,
422 ForceRValue)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000423 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000424 // C++ [over.ics.user]p4:
425 // A conversion of an expression of class type to the same class
426 // type is given Exact Match rank, and a conversion of an
427 // expression of class type to a base class of that type is
428 // given Conversion rank, in spite of the fact that a copy
429 // constructor (i.e., a user-defined conversion function) is
430 // called for those cases.
431 if (CXXConstructorDecl *Constructor
432 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Douglas Gregord9176392009-02-02 22:11:10 +0000433 QualType FromCanon
434 = Context.getCanonicalType(From->getType().getUnqualifiedType());
435 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
436 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000437 // Turn this into a "standard" conversion sequence, so that it
438 // gets ranked with standard conversion sequences.
Douglas Gregore640ab62008-11-03 17:51:48 +0000439 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
440 ICS.Standard.setAsIdentityConversion();
441 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
442 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000443 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregord9176392009-02-02 22:11:10 +0000444 if (ToCanon != FromCanon)
Douglas Gregore640ab62008-11-03 17:51:48 +0000445 ICS.Standard.Second = ICK_Derived_To_Base;
446 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000447 }
Douglas Gregorb206cc42009-01-30 23:27:23 +0000448
449 // C++ [over.best.ics]p4:
450 // However, when considering the argument of a user-defined
451 // conversion function that is a candidate by 13.3.1.3 when
452 // invoked for the copying of the temporary in the second step
453 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
454 // 13.3.1.6 in all cases, only standard conversion sequences and
455 // ellipsis conversion sequences are allowed.
456 if (SuppressUserConversions &&
457 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
458 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000459 } else
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000460 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000461
462 return ICS;
463}
464
465/// IsStandardConversion - Determines whether there is a standard
466/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
467/// expression From to the type ToType. Standard conversion sequences
468/// only consider non-class types; for conversions that involve class
469/// types, use TryImplicitConversion. If a conversion exists, SCS will
470/// contain the standard conversion sequence required to perform this
471/// conversion and this routine will return true. Otherwise, this
472/// routine will return false and the value of SCS is unspecified.
473bool
474Sema::IsStandardConversion(Expr* From, QualType ToType,
475 StandardConversionSequence &SCS)
476{
Douglas Gregord2baafd2008-10-21 16:13:35 +0000477 QualType FromType = From->getType();
478
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000479 // Standard conversions (C++ [conv])
Douglas Gregor70d26122008-11-12 17:17:38 +0000480 SCS.setAsIdentityConversion();
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000481 SCS.Deprecated = false;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000482 SCS.IncompatibleObjC = false;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000483 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000484 SCS.CopyConstructor = 0;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000485
Douglas Gregorfcb19192009-02-11 23:02:49 +0000486 // There are no standard conversions for class types in C++, so
487 // abort early. When overloading in C, however, we do permit
488 if (FromType->isRecordType() || ToType->isRecordType()) {
489 if (getLangOptions().CPlusPlus)
490 return false;
491
492 // When we're overloading in C, we allow, as standard conversions,
493 }
494
Douglas Gregord2baafd2008-10-21 16:13:35 +0000495 // The first conversion can be an lvalue-to-rvalue conversion,
496 // array-to-pointer conversion, or function-to-pointer conversion
497 // (C++ 4p1).
498
499 // Lvalue-to-rvalue conversion (C++ 4.1):
500 // An lvalue (3.10) of a non-function, non-array type T can be
501 // converted to an rvalue.
502 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
503 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor45014fd2008-11-10 20:40:00 +0000504 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000505 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000506 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000507
508 // If T is a non-class type, the type of the rvalue is the
509 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorfcb19192009-02-11 23:02:49 +0000510 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
511 // just strip the qualifiers because they don't matter.
512
513 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000514 FromType = FromType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000515 } else if (FromType->isArrayType()) {
516 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000517 SCS.First = ICK_Array_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000518
519 // An lvalue or rvalue of type "array of N T" or "array of unknown
520 // bound of T" can be converted to an rvalue of type "pointer to
521 // T" (C++ 4.2p1).
522 FromType = Context.getArrayDecayedType(FromType);
523
524 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
525 // This conversion is deprecated. (C++ D.4).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000526 SCS.Deprecated = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000527
528 // For the purpose of ranking in overload resolution
529 // (13.3.3.1.1), this conversion is considered an
530 // array-to-pointer conversion followed by a qualification
531 // conversion (4.4). (C++ 4.2p2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000532 SCS.Second = ICK_Identity;
533 SCS.Third = ICK_Qualification;
534 SCS.ToTypePtr = ToType.getAsOpaquePtr();
535 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000536 }
Mike Stump90fc78e2009-08-04 21:02:39 +0000537 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
538 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000539 SCS.First = ICK_Function_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000540
541 // An lvalue of function type T can be converted to an rvalue of
542 // type "pointer to T." The result is a pointer to the
543 // function. (C++ 4.3p1).
544 FromType = Context.getPointerType(FromType);
Mike Stump90fc78e2009-08-04 21:02:39 +0000545 } else if (FunctionDecl *Fn
Douglas Gregor45014fd2008-11-10 20:40:00 +0000546 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000547 // Address of overloaded function (C++ [over.over]).
Douglas Gregor45014fd2008-11-10 20:40:00 +0000548 SCS.First = ICK_Function_To_Pointer;
549
550 // We were able to resolve the address of the overloaded function,
551 // so we can convert to the type of that function.
552 FromType = Fn->getType();
Sebastian Redlce6fff02009-03-16 23:22:08 +0000553 if (ToType->isLValueReferenceType())
554 FromType = Context.getLValueReferenceType(FromType);
555 else if (ToType->isRValueReferenceType())
556 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl7434fc32009-02-04 21:23:32 +0000557 else if (ToType->isMemberPointerType()) {
558 // Resolve address only succeeds if both sides are member pointers,
559 // but it doesn't have to be the same class. See DR 247.
560 // Note that this means that the type of &Derived::fn can be
561 // Ret (Base::*)(Args) if the fn overload actually found is from the
562 // base class, even if it was brought into the derived class via a
563 // using declaration. The standard isn't clear on this issue at all.
564 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
565 FromType = Context.getMemberPointerType(FromType,
566 Context.getTypeDeclType(M->getParent()).getTypePtr());
567 } else
Douglas Gregor45014fd2008-11-10 20:40:00 +0000568 FromType = Context.getPointerType(FromType);
Mike Stump90fc78e2009-08-04 21:02:39 +0000569 } else {
570 // We don't require any conversions for the first step.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000571 SCS.First = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000572 }
573
574 // The second conversion can be an integral promotion, floating
575 // point promotion, integral conversion, floating point conversion,
576 // floating-integral conversion, pointer conversion,
577 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorfcb19192009-02-11 23:02:49 +0000578 // For overloading in C, this can also be a "compatible-type"
579 // conversion.
Douglas Gregor6fd35572008-12-19 17:40:08 +0000580 bool IncompatibleObjC = false;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000581 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000582 // The unqualified versions of the types are the same: there's no
583 // conversion to do.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000584 SCS.Second = ICK_Identity;
Mike Stump90fc78e2009-08-04 21:02:39 +0000585 } else if (IsIntegralPromotion(From, FromType, ToType)) {
586 // Integral promotion (C++ 4.5).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000587 SCS.Second = ICK_Integral_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000588 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000589 } else if (IsFloatingPointPromotion(FromType, ToType)) {
590 // Floating point promotion (C++ 4.6).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000591 SCS.Second = ICK_Floating_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000592 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000593 } else if (IsComplexPromotion(FromType, ToType)) {
594 // Complex promotion (Clang extension)
Douglas Gregore819caf2009-02-12 00:15:05 +0000595 SCS.Second = ICK_Complex_Promotion;
596 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000597 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000598 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000599 // Integral conversions (C++ 4.7).
600 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000601 SCS.Second = ICK_Integral_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000602 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000603 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
604 // Floating point conversions (C++ 4.8).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000605 SCS.Second = ICK_Floating_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000606 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000607 } else if (FromType->isComplexType() && ToType->isComplexType()) {
608 // Complex conversions (C99 6.3.1.6)
Douglas Gregore819caf2009-02-12 00:15:05 +0000609 SCS.Second = ICK_Complex_Conversion;
610 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000611 } else if ((FromType->isFloatingType() &&
612 ToType->isIntegralType() && (!ToType->isBooleanType() &&
613 !ToType->isEnumeralType())) ||
614 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
615 ToType->isFloatingType())) {
616 // Floating-integral conversions (C++ 4.9).
617 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000618 SCS.Second = ICK_Floating_Integral;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000619 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000620 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
621 (ToType->isComplexType() && FromType->isArithmeticType())) {
622 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregore819caf2009-02-12 00:15:05 +0000623 SCS.Second = ICK_Complex_Real;
624 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000625 } else if (IsPointerConversion(From, FromType, ToType, FromType,
626 IncompatibleObjC)) {
627 // Pointer conversions (C++ 4.10).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000628 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000629 SCS.IncompatibleObjC = IncompatibleObjC;
Mike Stump90fc78e2009-08-04 21:02:39 +0000630 } else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
631 // Pointer to member conversions (4.11).
Sebastian Redlba387562009-01-25 19:43:20 +0000632 SCS.Second = ICK_Pointer_Member;
Mike Stump90fc78e2009-08-04 21:02:39 +0000633 } else if (ToType->isBooleanType() &&
634 (FromType->isArithmeticType() ||
635 FromType->isEnumeralType() ||
636 FromType->isPointerType() ||
637 FromType->isBlockPointerType() ||
638 FromType->isMemberPointerType() ||
639 FromType->isNullPtrType())) {
640 // Boolean conversions (C++ 4.12).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000641 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000642 FromType = Context.BoolTy;
Mike Stump90fc78e2009-08-04 21:02:39 +0000643 } else if (!getLangOptions().CPlusPlus &&
644 Context.typesAreCompatible(ToType, FromType)) {
645 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorfcb19192009-02-11 23:02:49 +0000646 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000647 } else {
648 // No second conversion required.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000649 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000650 }
651
Douglas Gregor81c29152008-10-29 00:13:59 +0000652 QualType CanonFrom;
653 QualType CanonTo;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000654 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000655 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000656 SCS.Third = ICK_Qualification;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000657 FromType = ToType;
Douglas Gregor81c29152008-10-29 00:13:59 +0000658 CanonFrom = Context.getCanonicalType(FromType);
659 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000660 } else {
661 // No conversion required
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000662 SCS.Third = ICK_Identity;
663
664 // C++ [over.best.ics]p6:
665 // [...] Any difference in top-level cv-qualification is
666 // subsumed by the initialization itself and does not constitute
667 // a conversion. [...]
Douglas Gregor81c29152008-10-29 00:13:59 +0000668 CanonFrom = Context.getCanonicalType(FromType);
669 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000670 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor81c29152008-10-29 00:13:59 +0000671 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
672 FromType = ToType;
673 CanonFrom = CanonTo;
674 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000675 }
676
677 // If we have not converted the argument type to the parameter type,
678 // this is a bad conversion sequence.
Douglas Gregor81c29152008-10-29 00:13:59 +0000679 if (CanonFrom != CanonTo)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000680 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000681
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000682 SCS.ToTypePtr = FromType.getAsOpaquePtr();
683 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000684}
685
686/// IsIntegralPromotion - Determines whether the conversion from the
687/// expression From (whose potentially-adjusted type is FromType) to
688/// ToType is an integral promotion (C++ 4.5). If so, returns true and
689/// sets PromotedType to the promoted type.
690bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
691{
692 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redl12aee862008-11-04 15:59:10 +0000693 // All integers are built-in.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000694 if (!To) {
695 return false;
696 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000697
698 // An rvalue of type char, signed char, unsigned char, short int, or
699 // unsigned short int can be converted to an rvalue of type int if
700 // int can represent all the values of the source type; otherwise,
701 // the source rvalue can be converted to an rvalue of type unsigned
702 // int (C++ 4.5p1).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000703 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000704 if (// We can promote any signed, promotable integer type to an int
705 (FromType->isSignedIntegerType() ||
706 // We can promote any unsigned integer type whose size is
707 // less than int to an int.
708 (!FromType->isSignedIntegerType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000709 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000710 return To->getKind() == BuiltinType::Int;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000711 }
712
Douglas Gregord2baafd2008-10-21 16:13:35 +0000713 return To->getKind() == BuiltinType::UInt;
714 }
715
716 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
717 // can be converted to an rvalue of the first of the following types
718 // that can represent all the values of its underlying type: int,
719 // unsigned int, long, or unsigned long (C++ 4.5p2).
720 if ((FromType->isEnumeralType() || FromType->isWideCharType())
721 && ToType->isIntegerType()) {
722 // Determine whether the type we're converting from is signed or
723 // unsigned.
724 bool FromIsSigned;
725 uint64_t FromSize = Context.getTypeSize(FromType);
726 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
727 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
728 FromIsSigned = UnderlyingType->isSignedIntegerType();
729 } else {
730 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
731 FromIsSigned = true;
732 }
733
734 // The types we'll try to promote to, in the appropriate
735 // order. Try each of these types.
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000736 QualType PromoteTypes[6] = {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000737 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000738 Context.LongTy, Context.UnsignedLongTy ,
739 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregord2baafd2008-10-21 16:13:35 +0000740 };
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000741 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000742 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
743 if (FromSize < ToSize ||
744 (FromSize == ToSize &&
745 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
746 // We found the type that we can promote to. If this is the
747 // type we wanted, we have a promotion. Otherwise, no
748 // promotion.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000749 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregord2baafd2008-10-21 16:13:35 +0000750 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
751 }
752 }
753 }
754
755 // An rvalue for an integral bit-field (9.6) can be converted to an
756 // rvalue of type int if int can represent all the values of the
757 // bit-field; otherwise, it can be converted to unsigned int if
758 // unsigned int can represent all the values of the bit-field. If
759 // the bit-field is larger yet, no integral promotion applies to
760 // it. If the bit-field has an enumerated type, it is treated as any
761 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stumpe127ae32009-05-16 07:39:55 +0000762 // FIXME: We should delay checking of bit-fields until we actually perform the
763 // conversion.
Douglas Gregor531434b2009-05-02 02:18:30 +0000764 using llvm::APSInt;
765 if (From)
766 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor82d44772008-12-20 23:49:58 +0000767 APSInt BitWidth;
Douglas Gregor531434b2009-05-02 02:18:30 +0000768 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
769 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
770 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
771 ToSize = Context.getTypeSize(ToType);
Douglas Gregor82d44772008-12-20 23:49:58 +0000772
773 // Are we promoting to an int from a bitfield that fits in an int?
774 if (BitWidth < ToSize ||
775 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
776 return To->getKind() == BuiltinType::Int;
777 }
778
779 // Are we promoting to an unsigned int from an unsigned bitfield
780 // that fits into an unsigned int?
781 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
782 return To->getKind() == BuiltinType::UInt;
783 }
784
785 return false;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000786 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000787 }
Douglas Gregor531434b2009-05-02 02:18:30 +0000788
Douglas Gregord2baafd2008-10-21 16:13:35 +0000789 // An rvalue of type bool can be converted to an rvalue of type int,
790 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000791 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000792 return true;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000793 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000794
795 return false;
796}
797
798/// IsFloatingPointPromotion - Determines whether the conversion from
799/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
800/// returns true and sets PromotedType to the promoted type.
801bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
802{
803 /// An rvalue of type float can be converted to an rvalue of type
804 /// double. (C++ 4.6p1).
805 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregore819caf2009-02-12 00:15:05 +0000806 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000807 if (FromBuiltin->getKind() == BuiltinType::Float &&
808 ToBuiltin->getKind() == BuiltinType::Double)
809 return true;
810
Douglas Gregore819caf2009-02-12 00:15:05 +0000811 // C99 6.3.1.5p1:
812 // When a float is promoted to double or long double, or a
813 // double is promoted to long double [...].
814 if (!getLangOptions().CPlusPlus &&
815 (FromBuiltin->getKind() == BuiltinType::Float ||
816 FromBuiltin->getKind() == BuiltinType::Double) &&
817 (ToBuiltin->getKind() == BuiltinType::LongDouble))
818 return true;
819 }
820
Douglas Gregord2baafd2008-10-21 16:13:35 +0000821 return false;
822}
823
Douglas Gregore819caf2009-02-12 00:15:05 +0000824/// \brief Determine if a conversion is a complex promotion.
825///
826/// A complex promotion is defined as a complex -> complex conversion
827/// where the conversion between the underlying real types is a
Douglas Gregor4ff48512009-02-12 00:26:06 +0000828/// floating-point or integral promotion.
Douglas Gregore819caf2009-02-12 00:15:05 +0000829bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
830 const ComplexType *FromComplex = FromType->getAsComplexType();
831 if (!FromComplex)
832 return false;
833
834 const ComplexType *ToComplex = ToType->getAsComplexType();
835 if (!ToComplex)
836 return false;
837
838 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor4ff48512009-02-12 00:26:06 +0000839 ToComplex->getElementType()) ||
840 IsIntegralPromotion(0, FromComplex->getElementType(),
841 ToComplex->getElementType());
Douglas Gregore819caf2009-02-12 00:15:05 +0000842}
843
Douglas Gregor24a90a52008-11-26 23:31:11 +0000844/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
845/// the pointer type FromPtr to a pointer to type ToPointee, with the
846/// same type qualifiers as FromPtr has on its pointee type. ToType,
847/// if non-empty, will be a pointer to ToType that may or may not have
848/// the right set of qualifiers on its pointee.
849static QualType
850BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
851 QualType ToPointee, QualType ToType,
852 ASTContext &Context) {
853 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
854 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
855 unsigned Quals = CanonFromPointee.getCVRQualifiers();
856
857 // Exact qualifier match -> return the pointer type we're converting to.
858 if (CanonToPointee.getCVRQualifiers() == Quals) {
859 // ToType is exactly what we need. Return it.
860 if (ToType.getTypePtr())
861 return ToType;
862
863 // Build a pointer to ToPointee. It has the right qualifiers
864 // already.
865 return Context.getPointerType(ToPointee);
866 }
867
868 // Just build a canonical type that has the right qualifiers.
869 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
870}
871
Douglas Gregord2baafd2008-10-21 16:13:35 +0000872/// IsPointerConversion - Determines whether the conversion of the
873/// expression From, which has the (possibly adjusted) type FromType,
874/// can be converted to the type ToType via a pointer conversion (C++
875/// 4.10). If so, returns true and places the converted type (that
876/// might differ from ToType in its cv-qualifiers at some level) into
877/// ConvertedType.
Douglas Gregor9036ef72008-11-27 00:15:41 +0000878///
Douglas Gregor3f5a00c2008-11-27 01:19:21 +0000879/// This routine also supports conversions to and from block pointers
880/// and conversions with Objective-C's 'id', 'id<protocols...>', and
881/// pointers to interfaces. FIXME: Once we've determined the
882/// appropriate overloading rules for Objective-C, we may want to
883/// split the Objective-C checks into a different routine; however,
884/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor6fd35572008-12-19 17:40:08 +0000885/// conversions, so for now they live here. IncompatibleObjC will be
886/// set if the conversion is an allowed Objective-C conversion that
887/// should result in a warning.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000888bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000889 QualType& ConvertedType,
890 bool &IncompatibleObjC)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000891{
Douglas Gregor6fd35572008-12-19 17:40:08 +0000892 IncompatibleObjC = false;
Douglas Gregor932778b2008-12-19 19:13:09 +0000893 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
894 return true;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000895
Douglas Gregorf1d75712008-12-22 20:51:52 +0000896 // Conversion from a null pointer constant to any Objective-C pointer type.
Steve Naroffad75bd22009-07-16 15:41:00 +0000897 if (ToType->isObjCObjectPointerType() &&
Douglas Gregorf1d75712008-12-22 20:51:52 +0000898 From->isNullPointerConstant(Context)) {
899 ConvertedType = ToType;
900 return true;
901 }
902
Douglas Gregor9036ef72008-11-27 00:15:41 +0000903 // Blocks: Block pointers can be converted to void*.
904 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000905 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor9036ef72008-11-27 00:15:41 +0000906 ConvertedType = ToType;
907 return true;
908 }
909 // Blocks: A null pointer constant can be converted to a block
910 // pointer type.
911 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
912 ConvertedType = ToType;
913 return true;
914 }
915
Sebastian Redl5d0ead72009-05-10 18:38:11 +0000916 // If the left-hand-side is nullptr_t, the right side can be a null
917 // pointer constant.
918 if (ToType->isNullPtrType() && From->isNullPointerConstant(Context)) {
919 ConvertedType = ToType;
920 return true;
921 }
922
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000923 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregord2baafd2008-10-21 16:13:35 +0000924 if (!ToTypePtr)
925 return false;
926
927 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
928 if (From->isNullPointerConstant(Context)) {
929 ConvertedType = ToType;
930 return true;
931 }
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000932
Douglas Gregor24a90a52008-11-26 23:31:11 +0000933 // Beyond this point, both types need to be pointers.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000934 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor24a90a52008-11-26 23:31:11 +0000935 if (!FromTypePtr)
936 return false;
937
938 QualType FromPointeeType = FromTypePtr->getPointeeType();
939 QualType ToPointeeType = ToTypePtr->getPointeeType();
940
Douglas Gregord2baafd2008-10-21 16:13:35 +0000941 // An rvalue of type "pointer to cv T," where T is an object type,
942 // can be converted to an rvalue of type "pointer to cv void" (C++
943 // 4.10p2).
Douglas Gregor26ea1222009-03-24 20:32:41 +0000944 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000945 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
946 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000947 ToType, Context);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000948 return true;
949 }
950
Douglas Gregorfcb19192009-02-11 23:02:49 +0000951 // When we're overloading in C, we allow a special kind of pointer
952 // conversion for compatible-but-not-identical pointee types.
953 if (!getLangOptions().CPlusPlus &&
954 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
955 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
956 ToPointeeType,
957 ToType, Context);
958 return true;
959 }
960
Douglas Gregor14046502008-10-23 00:40:37 +0000961 // C++ [conv.ptr]p3:
962 //
963 // An rvalue of type "pointer to cv D," where D is a class type,
964 // can be converted to an rvalue of type "pointer to cv B," where
965 // B is a base class (clause 10) of D. If B is an inaccessible
966 // (clause 11) or ambiguous (10.2) base class of D, a program that
967 // necessitates this conversion is ill-formed. The result of the
968 // conversion is a pointer to the base class sub-object of the
969 // derived class object. The null pointer value is converted to
970 // the null pointer value of the destination type.
971 //
Douglas Gregorbb461502008-10-24 04:54:22 +0000972 // Note that we do not check for ambiguity or inaccessibility
973 // here. That is handled by CheckPointerConversion.
Douglas Gregorfcb19192009-02-11 23:02:49 +0000974 if (getLangOptions().CPlusPlus &&
975 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor24a90a52008-11-26 23:31:11 +0000976 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000977 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
978 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000979 ToType, Context);
980 return true;
981 }
Douglas Gregor14046502008-10-23 00:40:37 +0000982
Douglas Gregor932778b2008-12-19 19:13:09 +0000983 return false;
984}
985
986/// isObjCPointerConversion - Determines whether this is an
987/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
988/// with the same arguments and return values.
989bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
990 QualType& ConvertedType,
991 bool &IncompatibleObjC) {
992 if (!getLangOptions().ObjC1)
993 return false;
994
Steve Naroff329ec222009-07-10 23:34:53 +0000995 // First, we handle all conversions on ObjC object pointer types.
996 const ObjCObjectPointerType* ToObjCPtr = ToType->getAsObjCObjectPointerType();
997 const ObjCObjectPointerType *FromObjCPtr =
998 FromType->getAsObjCObjectPointerType();
Douglas Gregor932778b2008-12-19 19:13:09 +0000999
Steve Naroff329ec222009-07-10 23:34:53 +00001000 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff7bffd372009-07-15 18:40:39 +00001001 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff329ec222009-07-10 23:34:53 +00001002 // pointer to any interface (in both directions).
Steve Naroff7bffd372009-07-15 18:40:39 +00001003 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00001004 ConvertedType = ToType;
1005 return true;
1006 }
1007 // Conversions with Objective-C's id<...>.
1008 if ((FromObjCPtr->isObjCQualifiedIdType() ||
1009 ToObjCPtr->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00001010 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
1011 /*compare=*/false)) {
Steve Naroff329ec222009-07-10 23:34:53 +00001012 ConvertedType = ToType;
1013 return true;
1014 }
1015 // Objective C++: We're able to convert from a pointer to an
1016 // interface to a pointer to a different interface.
1017 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1018 ConvertedType = ToType;
1019 return true;
1020 }
1021
1022 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1023 // Okay: this is some kind of implicit downcast of Objective-C
1024 // interfaces, which is permitted. However, we're going to
1025 // complain about it.
1026 IncompatibleObjC = true;
1027 ConvertedType = FromType;
1028 return true;
1029 }
1030 }
1031 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor80402cf2008-12-23 00:53:59 +00001032 QualType ToPointeeType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001033 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff329ec222009-07-10 23:34:53 +00001034 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001035 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor80402cf2008-12-23 00:53:59 +00001036 ToPointeeType = ToBlockPtr->getPointeeType();
1037 else
Douglas Gregor932778b2008-12-19 19:13:09 +00001038 return false;
1039
Douglas Gregor80402cf2008-12-23 00:53:59 +00001040 QualType FromPointeeType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001041 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff329ec222009-07-10 23:34:53 +00001042 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001043 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor80402cf2008-12-23 00:53:59 +00001044 FromPointeeType = FromBlockPtr->getPointeeType();
1045 else
Douglas Gregor932778b2008-12-19 19:13:09 +00001046 return false;
1047
Douglas Gregor932778b2008-12-19 19:13:09 +00001048 // If we have pointers to pointers, recursively check whether this
1049 // is an Objective-C conversion.
1050 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1051 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1052 IncompatibleObjC)) {
1053 // We always complain about this conversion.
1054 IncompatibleObjC = true;
1055 ConvertedType = ToType;
1056 return true;
1057 }
Douglas Gregor80402cf2008-12-23 00:53:59 +00001058 // If we have pointers to functions or blocks, check whether the only
Douglas Gregor932778b2008-12-19 19:13:09 +00001059 // differences in the argument and result types are in Objective-C
1060 // pointer conversions. If so, we permit the conversion (but
1061 // complain about it).
Douglas Gregor4fa58902009-02-26 23:50:07 +00001062 const FunctionProtoType *FromFunctionType
1063 = FromPointeeType->getAsFunctionProtoType();
1064 const FunctionProtoType *ToFunctionType
1065 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregor932778b2008-12-19 19:13:09 +00001066 if (FromFunctionType && ToFunctionType) {
1067 // If the function types are exactly the same, this isn't an
1068 // Objective-C pointer conversion.
1069 if (Context.getCanonicalType(FromPointeeType)
1070 == Context.getCanonicalType(ToPointeeType))
1071 return false;
1072
1073 // Perform the quick checks that will tell us whether these
1074 // function types are obviously different.
1075 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1076 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1077 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1078 return false;
1079
1080 bool HasObjCConversion = false;
1081 if (Context.getCanonicalType(FromFunctionType->getResultType())
1082 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1083 // Okay, the types match exactly. Nothing to do.
1084 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1085 ToFunctionType->getResultType(),
1086 ConvertedType, IncompatibleObjC)) {
1087 // Okay, we have an Objective-C pointer conversion.
1088 HasObjCConversion = true;
1089 } else {
1090 // Function types are too different. Abort.
1091 return false;
1092 }
1093
1094 // Check argument types.
1095 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1096 ArgIdx != NumArgs; ++ArgIdx) {
1097 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1098 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1099 if (Context.getCanonicalType(FromArgType)
1100 == Context.getCanonicalType(ToArgType)) {
1101 // Okay, the types match exactly. Nothing to do.
1102 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1103 ConvertedType, IncompatibleObjC)) {
1104 // Okay, we have an Objective-C pointer conversion.
1105 HasObjCConversion = true;
1106 } else {
1107 // Argument types are too different. Abort.
1108 return false;
1109 }
1110 }
1111
1112 if (HasObjCConversion) {
1113 // We had an Objective-C conversion. Allow this pointer
1114 // conversion, but complain about it.
1115 ConvertedType = ToType;
1116 IncompatibleObjC = true;
1117 return true;
1118 }
1119 }
1120
Sebastian Redlba387562009-01-25 19:43:20 +00001121 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001122}
1123
Douglas Gregorbb461502008-10-24 04:54:22 +00001124/// CheckPointerConversion - Check the pointer conversion from the
1125/// expression From to the type ToType. This routine checks for
Sebastian Redl0e35d042009-07-25 15:41:38 +00001126/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregorbb461502008-10-24 04:54:22 +00001127/// conversions for which IsPointerConversion has already returned
1128/// true. It returns true and produces a diagnostic if there was an
1129/// error, or returns false otherwise.
1130bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1131 QualType FromType = From->getType();
1132
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001133 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1134 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregorbb461502008-10-24 04:54:22 +00001135 QualType FromPointeeType = FromPtrType->getPointeeType(),
1136 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregord0c653a2008-12-18 23:43:31 +00001137
Douglas Gregorbb461502008-10-24 04:54:22 +00001138 if (FromPointeeType->isRecordType() &&
1139 ToPointeeType->isRecordType()) {
1140 // We must have a derived-to-base conversion. Check an
1141 // ambiguous or inaccessible conversion.
Douglas Gregor651d1cc2008-10-24 16:17:19 +00001142 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1143 From->getExprLoc(),
1144 From->getSourceRange());
Douglas Gregorbb461502008-10-24 04:54:22 +00001145 }
1146 }
Steve Naroff329ec222009-07-10 23:34:53 +00001147 if (const ObjCObjectPointerType *FromPtrType =
1148 FromType->getAsObjCObjectPointerType())
1149 if (const ObjCObjectPointerType *ToPtrType =
1150 ToType->getAsObjCObjectPointerType()) {
1151 // Objective-C++ conversions are always okay.
1152 // FIXME: We should have a different class of conversions for the
1153 // Objective-C++ implicit conversions.
Steve Naroff7bffd372009-07-15 18:40:39 +00001154 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff329ec222009-07-10 23:34:53 +00001155 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +00001156
Steve Naroff329ec222009-07-10 23:34:53 +00001157 }
Douglas Gregorbb461502008-10-24 04:54:22 +00001158 return false;
1159}
1160
Sebastian Redlba387562009-01-25 19:43:20 +00001161/// IsMemberPointerConversion - Determines whether the conversion of the
1162/// expression From, which has the (possibly adjusted) type FromType, can be
1163/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1164/// If so, returns true and places the converted type (that might differ from
1165/// ToType in its cv-qualifiers at some level) into ConvertedType.
1166bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1167 QualType ToType, QualType &ConvertedType)
1168{
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001169 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redlba387562009-01-25 19:43:20 +00001170 if (!ToTypePtr)
1171 return false;
1172
1173 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1174 if (From->isNullPointerConstant(Context)) {
1175 ConvertedType = ToType;
1176 return true;
1177 }
1178
1179 // Otherwise, both types have to be member pointers.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001180 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redlba387562009-01-25 19:43:20 +00001181 if (!FromTypePtr)
1182 return false;
1183
1184 // A pointer to member of B can be converted to a pointer to member of D,
1185 // where D is derived from B (C++ 4.11p2).
1186 QualType FromClass(FromTypePtr->getClass(), 0);
1187 QualType ToClass(ToTypePtr->getClass(), 0);
1188 // FIXME: What happens when these are dependent? Is this function even called?
1189
1190 if (IsDerivedFrom(ToClass, FromClass)) {
1191 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1192 ToClass.getTypePtr());
1193 return true;
1194 }
1195
1196 return false;
1197}
1198
1199/// CheckMemberPointerConversion - Check the member pointer conversion from the
1200/// expression From to the type ToType. This routine checks for ambiguous or
1201/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1202/// for which IsMemberPointerConversion has already returned true. It returns
1203/// true and produces a diagnostic if there was an error, or returns false
1204/// otherwise.
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001205bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
1206 CastExpr::CastKind &Kind) {
Sebastian Redlba387562009-01-25 19:43:20 +00001207 QualType FromType = From->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001208 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001209 if (!FromPtrType) {
1210 // This must be a null pointer to member pointer conversion
1211 assert(From->isNullPointerConstant(Context) &&
1212 "Expr must be null pointer constant!");
1213 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001214 return false;
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001215 }
Sebastian Redlba387562009-01-25 19:43:20 +00001216
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001217 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001218 assert(ToPtrType && "No member pointer cast has a target type "
1219 "that is not a member pointer.");
Sebastian Redlba387562009-01-25 19:43:20 +00001220
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001221 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1222 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redlba387562009-01-25 19:43:20 +00001223
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001224 // FIXME: What about dependent types?
1225 assert(FromClass->isRecordType() && "Pointer into non-class.");
1226 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redlba387562009-01-25 19:43:20 +00001227
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001228 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1229 /*DetectVirtual=*/true);
1230 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1231 assert(DerivationOkay &&
1232 "Should not have been called if derivation isn't OK.");
1233 (void)DerivationOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001234
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001235 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1236 getUnqualifiedType())) {
1237 // Derivation is ambiguous. Redo the check to find the exact paths.
1238 Paths.clear();
1239 Paths.setRecordingPaths(true);
1240 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1241 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1242 (void)StillOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001243
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001244 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1245 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1246 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1247 return true;
Sebastian Redlba387562009-01-25 19:43:20 +00001248 }
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001249
Douglas Gregor2e047592009-02-28 01:32:25 +00001250 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001251 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1252 << FromClass << ToClass << QualType(VBase, 0)
1253 << From->getSourceRange();
1254 return true;
1255 }
1256
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001257 // Must be a base to derived member conversion.
1258 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redlba387562009-01-25 19:43:20 +00001259 return false;
1260}
1261
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001262/// IsQualificationConversion - Determines whether the conversion from
1263/// an rvalue of type FromType to ToType is a qualification conversion
1264/// (C++ 4.4).
1265bool
1266Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1267{
1268 FromType = Context.getCanonicalType(FromType);
1269 ToType = Context.getCanonicalType(ToType);
1270
1271 // If FromType and ToType are the same type, this is not a
1272 // qualification conversion.
1273 if (FromType == ToType)
1274 return false;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001275
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001276 // (C++ 4.4p4):
1277 // A conversion can add cv-qualifiers at levels other than the first
1278 // in multi-level pointers, subject to the following rules: [...]
1279 bool PreviousToQualsIncludeConst = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001280 bool UnwrappedAnyPointer = false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001281 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001282 // Within each iteration of the loop, we check the qualifiers to
1283 // determine if this still looks like a qualification
1284 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001285 // pointers or pointers-to-members and do it all again
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001286 // until there are no more pointers or pointers-to-members left to
1287 // unwrap.
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001288 UnwrappedAnyPointer = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001289
1290 // -- for every j > 0, if const is in cv 1,j then const is in cv
1291 // 2,j, and similarly for volatile.
Douglas Gregore5db4f72008-10-22 00:38:21 +00001292 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001293 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001294
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001295 // -- if the cv 1,j and cv 2,j are different, then const is in
1296 // every cv for 0 < k < j.
1297 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001298 && !PreviousToQualsIncludeConst)
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001299 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001300
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001301 // Keep track of whether all prior cv-qualifiers in the "to" type
1302 // include const.
1303 PreviousToQualsIncludeConst
1304 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001305 }
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001306
1307 // We are left with FromType and ToType being the pointee types
1308 // after unwrapping the original FromType and ToType the same number
1309 // of types. If we unwrapped any pointers, and if FromType and
1310 // ToType have the same unqualified type (since we checked
1311 // qualifiers above), then this is a qualification conversion.
1312 return UnwrappedAnyPointer &&
1313 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1314}
1315
Douglas Gregor8c860df2009-08-21 23:19:43 +00001316/// \brief Given a function template or function, extract the function template
1317/// declaration (if any) and the underlying function declaration.
1318template<typename T>
1319static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1320 FunctionTemplateDecl *&FunctionTemplate) {
1321 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1322 if (FunctionTemplate)
1323 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1324 else
1325 Function = cast<T>(Orig);
1326}
1327
1328
Douglas Gregorb206cc42009-01-30 23:27:23 +00001329/// Determines whether there is a user-defined conversion sequence
1330/// (C++ [over.ics.user]) that converts expression From to the type
1331/// ToType. If such a conversion exists, User will contain the
1332/// user-defined conversion sequence that performs such a conversion
1333/// and this routine will return true. Otherwise, this routine returns
1334/// false and User is unspecified.
1335///
1336/// \param AllowConversionFunctions true if the conversion should
1337/// consider conversion functions at all. If false, only constructors
1338/// will be considered.
1339///
1340/// \param AllowExplicit true if the conversion should consider C++0x
1341/// "explicit" conversion functions as well as non-explicit conversion
1342/// functions (C++0x [class.conv.fct]p2).
Sebastian Redla55834a2009-04-12 17:16:29 +00001343///
1344/// \param ForceRValue true if the expression should be treated as an rvalue
1345/// for overload resolution.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001346bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001347 UserDefinedConversionSequence& User,
Douglas Gregorb206cc42009-01-30 23:27:23 +00001348 bool AllowConversionFunctions,
Sebastian Redla55834a2009-04-12 17:16:29 +00001349 bool AllowExplicit, bool ForceRValue)
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001350{
1351 OverloadCandidateSet CandidateSet;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001352 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001353 if (CXXRecordDecl *ToRecordDecl
1354 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1355 // C++ [over.match.ctor]p1:
1356 // When objects of class type are direct-initialized (8.5), or
1357 // copy-initialized from an expression of the same or a
1358 // derived class type (8.5), overload resolution selects the
1359 // constructor. [...] For copy-initialization, the candidate
1360 // functions are all the converting constructors (12.3.1) of
1361 // that class. The argument list is the expression-list within
1362 // the parentheses of the initializer.
1363 DeclarationName ConstructorName
1364 = Context.DeclarationNames.getCXXConstructorName(
1365 Context.getCanonicalType(ToType).getUnqualifiedType());
1366 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001367 for (llvm::tie(Con, ConEnd)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001368 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor2e047592009-02-28 01:32:25 +00001369 Con != ConEnd; ++Con) {
Douglas Gregor050cabf2009-08-21 18:42:58 +00001370 // Find the constructor (which may be a template).
1371 CXXConstructorDecl *Constructor = 0;
1372 FunctionTemplateDecl *ConstructorTmpl
1373 = dyn_cast<FunctionTemplateDecl>(*Con);
1374 if (ConstructorTmpl)
1375 Constructor
1376 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1377 else
1378 Constructor = cast<CXXConstructorDecl>(*Con);
1379
Fariborz Jahanian625fb9d2009-08-06 17:22:51 +00001380 if (!Constructor->isInvalidDecl() &&
Douglas Gregor050cabf2009-08-21 18:42:58 +00001381 Constructor->isConvertingConstructor()) {
1382 if (ConstructorTmpl)
1383 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
1384 1, CandidateSet,
1385 /*SuppressUserConversions=*/true,
1386 ForceRValue);
1387 else
1388 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1389 /*SuppressUserConversions=*/true, ForceRValue);
1390 }
Douglas Gregor2e047592009-02-28 01:32:25 +00001391 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001392 }
1393 }
1394
Douglas Gregorb206cc42009-01-30 23:27:23 +00001395 if (!AllowConversionFunctions) {
1396 // Don't allow any conversion functions to enter the overload set.
Anders Carlssona21e7872009-08-26 23:45:07 +00001397 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1398 PDiag(0)
1399 << From->getSourceRange())) {
Douglas Gregorb35c7992009-08-24 15:23:48 +00001400 // No conversion functions from incomplete types.
Douglas Gregor2e047592009-02-28 01:32:25 +00001401 } else if (const RecordType *FromRecordType
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001402 = From->getType()->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001403 if (CXXRecordDecl *FromRecordDecl
1404 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1405 // Add all of the conversion functions as candidates.
1406 // FIXME: Look for conversions in base classes!
1407 OverloadedFunctionDecl *Conversions
1408 = FromRecordDecl->getConversionFunctions();
1409 for (OverloadedFunctionDecl::function_iterator Func
1410 = Conversions->function_begin();
1411 Func != Conversions->function_end(); ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00001412 CXXConversionDecl *Conv;
1413 FunctionTemplateDecl *ConvTemplate;
1414 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1415 if (ConvTemplate)
1416 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1417 else
1418 Conv = dyn_cast<CXXConversionDecl>(*Func);
1419
1420 if (AllowExplicit || !Conv->isExplicit()) {
1421 if (ConvTemplate)
1422 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1423 CandidateSet);
1424 else
1425 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1426 }
Douglas Gregor2e047592009-02-28 01:32:25 +00001427 }
Douglas Gregor60714f92008-11-07 22:36:19 +00001428 }
1429 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001430
1431 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001432 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001433 case OR_Success:
1434 // Record the standard conversion we used and the conversion function.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001435 if (CXXConstructorDecl *Constructor
1436 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1437 // C++ [over.ics.user]p1:
1438 // If the user-defined conversion is specified by a
1439 // constructor (12.3.1), the initial standard conversion
1440 // sequence converts the source type to the type required by
1441 // the argument of the constructor.
1442 //
1443 // FIXME: What about ellipsis conversions?
1444 QualType ThisType = Constructor->getThisType(Context);
1445 User.Before = Best->Conversions[0].Standard;
1446 User.ConversionFunction = Constructor;
1447 User.After.setAsIdentityConversion();
1448 User.After.FromTypePtr
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001449 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001450 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1451 return true;
Douglas Gregor60714f92008-11-07 22:36:19 +00001452 } else if (CXXConversionDecl *Conversion
1453 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1454 // C++ [over.ics.user]p1:
1455 //
1456 // [...] If the user-defined conversion is specified by a
1457 // conversion function (12.3.2), the initial standard
1458 // conversion sequence converts the source type to the
1459 // implicit object parameter of the conversion function.
1460 User.Before = Best->Conversions[0].Standard;
1461 User.ConversionFunction = Conversion;
1462
1463 // C++ [over.ics.user]p2:
1464 // The second standard conversion sequence converts the
1465 // result of the user-defined conversion to the target type
1466 // for the sequence. Since an implicit conversion sequence
1467 // is an initialization, the special rules for
1468 // initialization by user-defined conversion apply when
1469 // selecting the best user-defined conversion for a
1470 // user-defined conversion sequence (see 13.3.3 and
1471 // 13.3.3.1).
1472 User.After = Best->FinalConversion;
1473 return true;
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001474 } else {
Douglas Gregor60714f92008-11-07 22:36:19 +00001475 assert(false && "Not a constructor or conversion function?");
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001476 return false;
1477 }
1478
1479 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00001480 case OR_Deleted:
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001481 // No conversion here! We're done.
1482 return false;
1483
1484 case OR_Ambiguous:
1485 // FIXME: See C++ [over.best.ics]p10 for the handling of
1486 // ambiguous conversion sequences.
1487 return false;
1488 }
1489
1490 return false;
1491}
1492
Douglas Gregord2baafd2008-10-21 16:13:35 +00001493/// CompareImplicitConversionSequences - Compare two implicit
1494/// conversion sequences to determine whether one is better than the
1495/// other or if they are indistinguishable (C++ 13.3.3.2).
1496ImplicitConversionSequence::CompareKind
1497Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1498 const ImplicitConversionSequence& ICS2)
1499{
1500 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1501 // conversion sequences (as defined in 13.3.3.1)
1502 // -- a standard conversion sequence (13.3.3.1.1) is a better
1503 // conversion sequence than a user-defined conversion sequence or
1504 // an ellipsis conversion sequence, and
1505 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1506 // conversion sequence than an ellipsis conversion sequence
1507 // (13.3.3.1.3).
1508 //
1509 if (ICS1.ConversionKind < ICS2.ConversionKind)
1510 return ImplicitConversionSequence::Better;
1511 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1512 return ImplicitConversionSequence::Worse;
1513
1514 // Two implicit conversion sequences of the same form are
1515 // indistinguishable conversion sequences unless one of the
1516 // following rules apply: (C++ 13.3.3.2p3):
1517 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1518 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1519 else if (ICS1.ConversionKind ==
1520 ImplicitConversionSequence::UserDefinedConversion) {
1521 // User-defined conversion sequence U1 is a better conversion
1522 // sequence than another user-defined conversion sequence U2 if
1523 // they contain the same user-defined conversion function or
1524 // constructor and if the second standard conversion sequence of
1525 // U1 is better than the second standard conversion sequence of
1526 // U2 (C++ 13.3.3.2p3).
1527 if (ICS1.UserDefined.ConversionFunction ==
1528 ICS2.UserDefined.ConversionFunction)
1529 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1530 ICS2.UserDefined.After);
1531 }
1532
1533 return ImplicitConversionSequence::Indistinguishable;
1534}
1535
1536/// CompareStandardConversionSequences - Compare two standard
1537/// conversion sequences to determine whether one is better than the
1538/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1539ImplicitConversionSequence::CompareKind
1540Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1541 const StandardConversionSequence& SCS2)
1542{
1543 // Standard conversion sequence S1 is a better conversion sequence
1544 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1545
1546 // -- S1 is a proper subsequence of S2 (comparing the conversion
1547 // sequences in the canonical form defined by 13.3.3.1.1,
1548 // excluding any Lvalue Transformation; the identity conversion
1549 // sequence is considered to be a subsequence of any
1550 // non-identity conversion sequence) or, if not that,
1551 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1552 // Neither is a proper subsequence of the other. Do nothing.
1553 ;
1554 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1555 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1556 (SCS1.Second == ICK_Identity &&
1557 SCS1.Third == ICK_Identity))
1558 // SCS1 is a proper subsequence of SCS2.
1559 return ImplicitConversionSequence::Better;
1560 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1561 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1562 (SCS2.Second == ICK_Identity &&
1563 SCS2.Third == ICK_Identity))
1564 // SCS2 is a proper subsequence of SCS1.
1565 return ImplicitConversionSequence::Worse;
1566
1567 // -- the rank of S1 is better than the rank of S2 (by the rules
1568 // defined below), or, if not that,
1569 ImplicitConversionRank Rank1 = SCS1.getRank();
1570 ImplicitConversionRank Rank2 = SCS2.getRank();
1571 if (Rank1 < Rank2)
1572 return ImplicitConversionSequence::Better;
1573 else if (Rank2 < Rank1)
1574 return ImplicitConversionSequence::Worse;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001575
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001576 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1577 // are indistinguishable unless one of the following rules
1578 // applies:
1579
1580 // A conversion that is not a conversion of a pointer, or
1581 // pointer to member, to bool is better than another conversion
1582 // that is such a conversion.
1583 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1584 return SCS2.isPointerConversionToBool()
1585 ? ImplicitConversionSequence::Better
1586 : ImplicitConversionSequence::Worse;
1587
Douglas Gregor14046502008-10-23 00:40:37 +00001588 // C++ [over.ics.rank]p4b2:
1589 //
1590 // If class B is derived directly or indirectly from class A,
Douglas Gregor0e343382008-10-29 14:50:44 +00001591 // conversion of B* to A* is better than conversion of B* to
1592 // void*, and conversion of A* to void* is better than conversion
1593 // of B* to void*.
Douglas Gregor14046502008-10-23 00:40:37 +00001594 bool SCS1ConvertsToVoid
1595 = SCS1.isPointerConversionToVoidPointer(Context);
1596 bool SCS2ConvertsToVoid
1597 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregor0e343382008-10-29 14:50:44 +00001598 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1599 // Exactly one of the conversion sequences is a conversion to
1600 // a void pointer; it's the worse conversion.
Douglas Gregor14046502008-10-23 00:40:37 +00001601 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1602 : ImplicitConversionSequence::Worse;
Douglas Gregor0e343382008-10-29 14:50:44 +00001603 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1604 // Neither conversion sequence converts to a void pointer; compare
1605 // their derived-to-base conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001606 if (ImplicitConversionSequence::CompareKind DerivedCK
1607 = CompareDerivedToBaseConversions(SCS1, SCS2))
1608 return DerivedCK;
Douglas Gregor0e343382008-10-29 14:50:44 +00001609 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1610 // Both conversion sequences are conversions to void
1611 // pointers. Compare the source types to determine if there's an
1612 // inheritance relationship in their sources.
1613 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1614 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1615
1616 // Adjust the types we're converting from via the array-to-pointer
1617 // conversion, if we need to.
1618 if (SCS1.First == ICK_Array_To_Pointer)
1619 FromType1 = Context.getArrayDecayedType(FromType1);
1620 if (SCS2.First == ICK_Array_To_Pointer)
1621 FromType2 = Context.getArrayDecayedType(FromType2);
1622
1623 QualType FromPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001624 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor0e343382008-10-29 14:50:44 +00001625 QualType FromPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001626 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor0e343382008-10-29 14:50:44 +00001627
1628 if (IsDerivedFrom(FromPointee2, FromPointee1))
1629 return ImplicitConversionSequence::Better;
1630 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1631 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001632
1633 // Objective-C++: If one interface is more specific than the
1634 // other, it is the better one.
1635 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1636 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1637 if (FromIface1 && FromIface1) {
1638 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1639 return ImplicitConversionSequence::Better;
1640 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1641 return ImplicitConversionSequence::Worse;
1642 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001643 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001644
1645 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1646 // bullet 3).
Douglas Gregor14046502008-10-23 00:40:37 +00001647 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001648 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor14046502008-10-23 00:40:37 +00001649 return QualCK;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001650
Douglas Gregor0e343382008-10-29 14:50:44 +00001651 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001652 // C++0x [over.ics.rank]p3b4:
1653 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1654 // implicit object parameter of a non-static member function declared
1655 // without a ref-qualifier, and S1 binds an rvalue reference to an
1656 // rvalue and S2 binds an lvalue reference.
Sebastian Redldfc30332009-03-29 15:27:50 +00001657 // FIXME: We don't know if we're dealing with the implicit object parameter,
1658 // or if the member function in this case has a ref qualifier.
1659 // (Of course, we don't have ref qualifiers yet.)
1660 if (SCS1.RRefBinding != SCS2.RRefBinding)
1661 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1662 : ImplicitConversionSequence::Worse;
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001663
1664 // C++ [over.ics.rank]p3b4:
1665 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1666 // which the references refer are the same type except for
1667 // top-level cv-qualifiers, and the type to which the reference
1668 // initialized by S2 refers is more cv-qualified than the type
1669 // to which the reference initialized by S1 refers.
Sebastian Redldfc30332009-03-29 15:27:50 +00001670 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1671 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregor0e343382008-10-29 14:50:44 +00001672 T1 = Context.getCanonicalType(T1);
1673 T2 = Context.getCanonicalType(T2);
1674 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1675 if (T2.isMoreQualifiedThan(T1))
1676 return ImplicitConversionSequence::Better;
1677 else if (T1.isMoreQualifiedThan(T2))
1678 return ImplicitConversionSequence::Worse;
1679 }
1680 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001681
1682 return ImplicitConversionSequence::Indistinguishable;
1683}
1684
1685/// CompareQualificationConversions - Compares two standard conversion
1686/// sequences to determine whether they can be ranked based on their
1687/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1688ImplicitConversionSequence::CompareKind
1689Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1690 const StandardConversionSequence& SCS2)
1691{
Douglas Gregor4459bbe2008-10-22 15:04:37 +00001692 // C++ 13.3.3.2p3:
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001693 // -- S1 and S2 differ only in their qualification conversion and
1694 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1695 // cv-qualification signature of type T1 is a proper subset of
1696 // the cv-qualification signature of type T2, and S1 is not the
1697 // deprecated string literal array-to-pointer conversion (4.2).
1698 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1699 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1700 return ImplicitConversionSequence::Indistinguishable;
1701
1702 // FIXME: the example in the standard doesn't use a qualification
1703 // conversion (!)
1704 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1705 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1706 T1 = Context.getCanonicalType(T1);
1707 T2 = Context.getCanonicalType(T2);
1708
1709 // If the types are the same, we won't learn anything by unwrapped
1710 // them.
1711 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1712 return ImplicitConversionSequence::Indistinguishable;
1713
1714 ImplicitConversionSequence::CompareKind Result
1715 = ImplicitConversionSequence::Indistinguishable;
1716 while (UnwrapSimilarPointerTypes(T1, T2)) {
1717 // Within each iteration of the loop, we check the qualifiers to
1718 // determine if this still looks like a qualification
1719 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001720 // pointers or pointers-to-members and do it all again
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001721 // until there are no more pointers or pointers-to-members left
1722 // to unwrap. This essentially mimics what
1723 // IsQualificationConversion does, but here we're checking for a
1724 // strict subset of qualifiers.
1725 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1726 // The qualifiers are the same, so this doesn't tell us anything
1727 // about how the sequences rank.
1728 ;
1729 else if (T2.isMoreQualifiedThan(T1)) {
1730 // T1 has fewer qualifiers, so it could be the better sequence.
1731 if (Result == ImplicitConversionSequence::Worse)
1732 // Neither has qualifiers that are a subset of the other's
1733 // qualifiers.
1734 return ImplicitConversionSequence::Indistinguishable;
1735
1736 Result = ImplicitConversionSequence::Better;
1737 } else if (T1.isMoreQualifiedThan(T2)) {
1738 // T2 has fewer qualifiers, so it could be the better sequence.
1739 if (Result == ImplicitConversionSequence::Better)
1740 // Neither has qualifiers that are a subset of the other's
1741 // qualifiers.
1742 return ImplicitConversionSequence::Indistinguishable;
1743
1744 Result = ImplicitConversionSequence::Worse;
1745 } else {
1746 // Qualifiers are disjoint.
1747 return ImplicitConversionSequence::Indistinguishable;
1748 }
1749
1750 // If the types after this point are equivalent, we're done.
1751 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1752 break;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001753 }
1754
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001755 // Check that the winning standard conversion sequence isn't using
1756 // the deprecated string literal array to pointer conversion.
1757 switch (Result) {
1758 case ImplicitConversionSequence::Better:
1759 if (SCS1.Deprecated)
1760 Result = ImplicitConversionSequence::Indistinguishable;
1761 break;
1762
1763 case ImplicitConversionSequence::Indistinguishable:
1764 break;
1765
1766 case ImplicitConversionSequence::Worse:
1767 if (SCS2.Deprecated)
1768 Result = ImplicitConversionSequence::Indistinguishable;
1769 break;
1770 }
1771
1772 return Result;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001773}
1774
Douglas Gregor14046502008-10-23 00:40:37 +00001775/// CompareDerivedToBaseConversions - Compares two standard conversion
1776/// sequences to determine whether they can be ranked based on their
Douglas Gregor24a90a52008-11-26 23:31:11 +00001777/// various kinds of derived-to-base conversions (C++
1778/// [over.ics.rank]p4b3). As part of these checks, we also look at
1779/// conversions between Objective-C interface types.
Douglas Gregor14046502008-10-23 00:40:37 +00001780ImplicitConversionSequence::CompareKind
1781Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1782 const StandardConversionSequence& SCS2) {
1783 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1784 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1785 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1786 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1787
1788 // Adjust the types we're converting from via the array-to-pointer
1789 // conversion, if we need to.
1790 if (SCS1.First == ICK_Array_To_Pointer)
1791 FromType1 = Context.getArrayDecayedType(FromType1);
1792 if (SCS2.First == ICK_Array_To_Pointer)
1793 FromType2 = Context.getArrayDecayedType(FromType2);
1794
1795 // Canonicalize all of the types.
1796 FromType1 = Context.getCanonicalType(FromType1);
1797 ToType1 = Context.getCanonicalType(ToType1);
1798 FromType2 = Context.getCanonicalType(FromType2);
1799 ToType2 = Context.getCanonicalType(ToType2);
1800
Douglas Gregor0e343382008-10-29 14:50:44 +00001801 // C++ [over.ics.rank]p4b3:
Douglas Gregor14046502008-10-23 00:40:37 +00001802 //
1803 // If class B is derived directly or indirectly from class A and
1804 // class C is derived directly or indirectly from B,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001805 //
1806 // For Objective-C, we let A, B, and C also be Objective-C
1807 // interfaces.
Douglas Gregor0e343382008-10-29 14:50:44 +00001808
1809 // Compare based on pointer conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001810 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor3f5a00c2008-11-27 01:19:21 +00001811 SCS2.Second == ICK_Pointer_Conversion &&
1812 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1813 FromType1->isPointerType() && FromType2->isPointerType() &&
1814 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregor14046502008-10-23 00:40:37 +00001815 QualType FromPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001816 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001817 QualType ToPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001818 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001819 QualType FromPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001820 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001821 QualType ToPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001822 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor24a90a52008-11-26 23:31:11 +00001823
1824 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1825 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1826 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1827 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1828
Douglas Gregor0e343382008-10-29 14:50:44 +00001829 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor14046502008-10-23 00:40:37 +00001830 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1831 if (IsDerivedFrom(ToPointee1, ToPointee2))
1832 return ImplicitConversionSequence::Better;
1833 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1834 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001835
1836 if (ToIface1 && ToIface2) {
1837 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1838 return ImplicitConversionSequence::Better;
1839 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1840 return ImplicitConversionSequence::Worse;
1841 }
Douglas Gregor14046502008-10-23 00:40:37 +00001842 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001843
1844 // -- conversion of B* to A* is better than conversion of C* to A*,
1845 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1846 if (IsDerivedFrom(FromPointee2, FromPointee1))
1847 return ImplicitConversionSequence::Better;
1848 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1849 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001850
1851 if (FromIface1 && FromIface2) {
1852 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1853 return ImplicitConversionSequence::Better;
1854 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1855 return ImplicitConversionSequence::Worse;
1856 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001857 }
Douglas Gregor14046502008-10-23 00:40:37 +00001858 }
1859
Douglas Gregor0e343382008-10-29 14:50:44 +00001860 // Compare based on reference bindings.
1861 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1862 SCS1.Second == ICK_Derived_To_Base) {
1863 // -- binding of an expression of type C to a reference of type
1864 // B& is better than binding an expression of type C to a
1865 // reference of type A&,
1866 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1867 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1868 if (IsDerivedFrom(ToType1, ToType2))
1869 return ImplicitConversionSequence::Better;
1870 else if (IsDerivedFrom(ToType2, ToType1))
1871 return ImplicitConversionSequence::Worse;
1872 }
1873
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001874 // -- binding of an expression of type B to a reference of type
1875 // A& is better than binding an expression of type C to a
1876 // reference of type A&,
Douglas Gregor0e343382008-10-29 14:50:44 +00001877 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1878 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1879 if (IsDerivedFrom(FromType2, FromType1))
1880 return ImplicitConversionSequence::Better;
1881 else if (IsDerivedFrom(FromType1, FromType2))
1882 return ImplicitConversionSequence::Worse;
1883 }
1884 }
1885
1886
1887 // FIXME: conversion of A::* to B::* is better than conversion of
1888 // A::* to C::*,
1889
1890 // FIXME: conversion of B::* to C::* is better than conversion of
1891 // A::* to C::*, and
1892
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001893 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1894 SCS1.Second == ICK_Derived_To_Base) {
1895 // -- conversion of C to B is better than conversion of C to A,
1896 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1897 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1898 if (IsDerivedFrom(ToType1, ToType2))
1899 return ImplicitConversionSequence::Better;
1900 else if (IsDerivedFrom(ToType2, ToType1))
1901 return ImplicitConversionSequence::Worse;
1902 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001903
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001904 // -- conversion of B to A is better than conversion of C to A.
1905 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1906 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1907 if (IsDerivedFrom(FromType2, FromType1))
1908 return ImplicitConversionSequence::Better;
1909 else if (IsDerivedFrom(FromType1, FromType2))
1910 return ImplicitConversionSequence::Worse;
1911 }
1912 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001913
Douglas Gregor14046502008-10-23 00:40:37 +00001914 return ImplicitConversionSequence::Indistinguishable;
1915}
1916
Douglas Gregor81c29152008-10-29 00:13:59 +00001917/// TryCopyInitialization - Try to copy-initialize a value of type
1918/// ToType from the expression From. Return the implicit conversion
1919/// sequence required to pass this argument, which may be a bad
1920/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001921/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redla55834a2009-04-12 17:16:29 +00001922/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1923/// then we treat @p From as an rvalue, even if it is an lvalue.
Douglas Gregor81c29152008-10-29 00:13:59 +00001924ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001925Sema::TryCopyInitialization(Expr *From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001926 bool SuppressUserConversions, bool ForceRValue) {
Douglas Gregorfcb19192009-02-11 23:02:49 +00001927 if (ToType->isReferenceType()) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001928 ImplicitConversionSequence ICS;
Sebastian Redla55834a2009-04-12 17:16:29 +00001929 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions,
1930 /*AllowExplicit=*/false, ForceRValue);
Douglas Gregor81c29152008-10-29 00:13:59 +00001931 return ICS;
1932 } else {
Anders Carlssonf4a65092009-08-27 16:01:18 +00001933 unsigned Flags = ORF_None;
1934 if (SuppressUserConversions) Flags |= ORF_SuppressUserConversions;
1935 if (ForceRValue) Flags |= ORF_ForceRValue;
1936
1937 return TryImplicitConversion(From, ToType, Flags);
Douglas Gregor81c29152008-10-29 00:13:59 +00001938 }
1939}
1940
Sebastian Redla55834a2009-04-12 17:16:29 +00001941/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1942/// the expression @p From. Returns true (and emits a diagnostic) if there was
1943/// an error, returns false if the initialization succeeded. Elidable should
1944/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1945/// differently in C++0x for this case.
Douglas Gregor81c29152008-10-29 00:13:59 +00001946bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001947 const char* Flavor, bool Elidable) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001948 if (!getLangOptions().CPlusPlus) {
1949 // In C, argument passing is the same as performing an assignment.
1950 QualType FromType = From->getType();
Douglas Gregor144b06c2009-04-29 22:16:16 +00001951
Douglas Gregor81c29152008-10-29 00:13:59 +00001952 AssignConvertType ConvTy =
1953 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor144b06c2009-04-29 22:16:16 +00001954 if (ConvTy != Compatible &&
1955 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1956 ConvTy = Compatible;
1957
Douglas Gregor81c29152008-10-29 00:13:59 +00001958 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1959 FromType, From, Flavor);
Douglas Gregor81c29152008-10-29 00:13:59 +00001960 }
Sebastian Redla55834a2009-04-12 17:16:29 +00001961
Chris Lattner271d4c22008-11-24 05:29:24 +00001962 if (ToType->isReferenceType())
1963 return CheckReferenceInit(From, ToType);
1964
Sebastian Redla55834a2009-04-12 17:16:29 +00001965 if (!PerformImplicitConversion(From, ToType, Flavor,
1966 /*AllowExplicit=*/false, Elidable))
Chris Lattner271d4c22008-11-24 05:29:24 +00001967 return false;
Sebastian Redla55834a2009-04-12 17:16:29 +00001968
Chris Lattner271d4c22008-11-24 05:29:24 +00001969 return Diag(From->getSourceRange().getBegin(),
1970 diag::err_typecheck_convert_incompatible)
1971 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001972}
1973
Douglas Gregor5ed15042008-11-18 23:14:02 +00001974/// TryObjectArgumentInitialization - Try to initialize the object
1975/// parameter of the given member function (@c Method) from the
1976/// expression @p From.
1977ImplicitConversionSequence
1978Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1979 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1980 unsigned MethodQuals = Method->getTypeQualifiers();
1981 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1982
1983 // Set up the conversion sequence as a "bad" conversion, to allow us
1984 // to exit early.
1985 ImplicitConversionSequence ICS;
1986 ICS.Standard.setAsIdentityConversion();
1987 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1988
1989 // We need to have an object of class type.
1990 QualType FromType = From->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001991 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00001992 FromType = PT->getPointeeType();
1993
1994 assert(FromType->isRecordType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00001995
1996 // The implicit object parmeter is has the type "reference to cv X",
1997 // where X is the class of which the function is a member
1998 // (C++ [over.match.funcs]p4). However, when finding an implicit
1999 // conversion sequence for the argument, we are not allowed to
2000 // create temporaries or perform user-defined conversions
2001 // (C++ [over.match.funcs]p5). We perform a simplified version of
2002 // reference binding here, that allows class rvalues to bind to
2003 // non-constant references.
2004
2005 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2006 // with the implicit object parameter (C++ [over.match.funcs]p5).
2007 QualType FromTypeCanon = Context.getCanonicalType(FromType);
2008 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2009 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2010 return ICS;
2011
2012 // Check that we have either the same type or a derived type. It
2013 // affects the conversion rank.
2014 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2015 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2016 ICS.Standard.Second = ICK_Identity;
2017 else if (IsDerivedFrom(FromType, ClassType))
2018 ICS.Standard.Second = ICK_Derived_To_Base;
2019 else
2020 return ICS;
2021
2022 // Success. Mark this as a reference binding.
2023 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2024 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2025 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2026 ICS.Standard.ReferenceBinding = true;
2027 ICS.Standard.DirectBinding = true;
Sebastian Redl9bc16ad2009-03-29 22:46:24 +00002028 ICS.Standard.RRefBinding = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002029 return ICS;
2030}
2031
2032/// PerformObjectArgumentInitialization - Perform initialization of
2033/// the implicit object parameter for the given Method with the given
2034/// expression.
2035bool
2036Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002037 QualType FromRecordType, DestType;
2038 QualType ImplicitParamRecordType =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002039 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002040
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002041 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002042 FromRecordType = PT->getPointeeType();
2043 DestType = Method->getThisType(Context);
2044 } else {
2045 FromRecordType = From->getType();
2046 DestType = ImplicitParamRecordType;
2047 }
2048
Douglas Gregor5ed15042008-11-18 23:14:02 +00002049 ImplicitConversionSequence ICS
2050 = TryObjectArgumentInitialization(From, Method);
2051 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2052 return Diag(From->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002053 diag::err_implicit_object_parameter_init)
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002054 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2055
Douglas Gregor5ed15042008-11-18 23:14:02 +00002056 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002057 CheckDerivedToBaseConversion(FromRecordType,
2058 ImplicitParamRecordType,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002059 From->getSourceRange().getBegin(),
2060 From->getSourceRange()))
2061 return true;
2062
Anders Carlssone25b6cd2009-08-07 18:45:49 +00002063 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
2064 /*isLvalue=*/true);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002065 return false;
2066}
2067
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002068/// TryContextuallyConvertToBool - Attempt to contextually convert the
2069/// expression From to bool (C++0x [conv]p3).
2070ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Anders Carlssonf4a65092009-08-27 16:01:18 +00002071 return TryImplicitConversion(From, Context.BoolTy, ORF_AllowExplicit);
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002072}
2073
2074/// PerformContextuallyConvertToBool - Perform a contextual conversion
2075/// of the expression From to bool (C++0x [conv]p3).
2076bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2077 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2078 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2079 return false;
2080
2081 return Diag(From->getSourceRange().getBegin(),
2082 diag::err_typecheck_bool_condition)
2083 << From->getType() << From->getSourceRange();
2084}
2085
Douglas Gregord2baafd2008-10-21 16:13:35 +00002086/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002087/// candidate functions, using the given function call arguments. If
2088/// @p SuppressUserConversions, then don't allow user-defined
2089/// conversions via constructors or conversion operators.
Sebastian Redla55834a2009-04-12 17:16:29 +00002090/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2091/// hacky way to implement the overloading rules for elidable copy
2092/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregord2baafd2008-10-21 16:13:35 +00002093void
2094Sema::AddOverloadCandidate(FunctionDecl *Function,
2095 Expr **Args, unsigned NumArgs,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002096 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002097 bool SuppressUserConversions,
2098 bool ForceRValue)
Douglas Gregord2baafd2008-10-21 16:13:35 +00002099{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002100 const FunctionProtoType* Proto
2101 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregord2baafd2008-10-21 16:13:35 +00002102 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregor60714f92008-11-07 22:36:19 +00002103 assert(!isa<CXXConversionDecl>(Function) &&
2104 "Use AddConversionCandidate for conversion functions");
Douglas Gregorb60eb752009-06-25 22:08:12 +00002105 assert(!Function->getDescribedFunctionTemplate() &&
2106 "Use AddTemplateOverloadCandidate for function templates");
2107
Douglas Gregor3257fb52008-12-22 05:46:06 +00002108 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00002109 if (!isa<CXXConstructorDecl>(Method)) {
2110 // If we get here, it's because we're calling a member function
2111 // that is named without a member access expression (e.g.,
2112 // "this->f") that was either written explicitly or created
2113 // implicitly. This can happen with a qualified call to a member
2114 // function, e.g., X::f(). We use a NULL object as the implied
2115 // object argument (C++ [over.call.func]p3).
2116 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2117 SuppressUserConversions, ForceRValue);
2118 return;
2119 }
2120 // We treat a constructor like a non-member function, since its object
2121 // argument doesn't participate in overload resolution.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002122 }
2123
2124
Douglas Gregord2baafd2008-10-21 16:13:35 +00002125 // Add this candidate
2126 CandidateSet.push_back(OverloadCandidate());
2127 OverloadCandidate& Candidate = CandidateSet.back();
2128 Candidate.Function = Function;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002129 Candidate.Viable = true;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002130 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002131 Candidate.IgnoreObjectArgument = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00002132
2133 unsigned NumArgsInProto = Proto->getNumArgs();
2134
2135 // (C++ 13.3.2p2): A candidate function having fewer than m
2136 // parameters is viable only if it has an ellipsis in its parameter
2137 // list (8.3.5).
2138 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2139 Candidate.Viable = false;
2140 return;
2141 }
2142
2143 // (C++ 13.3.2p2): A candidate function having more than m parameters
2144 // is viable only if the (m+1)st parameter has a default argument
2145 // (8.3.6). For the purposes of overload resolution, the
2146 // parameter list is truncated on the right, so that there are
2147 // exactly m parameters.
2148 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2149 if (NumArgs < MinRequiredArgs) {
2150 // Not enough arguments.
2151 Candidate.Viable = false;
2152 return;
2153 }
2154
2155 // Determine the implicit conversion sequences for each of the
2156 // arguments.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002157 Candidate.Conversions.resize(NumArgs);
2158 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2159 if (ArgIdx < NumArgsInProto) {
2160 // (C++ 13.3.2p3): for F to be a viable function, there shall
2161 // exist for each argument an implicit conversion sequence
2162 // (13.3.3.1) that converts that argument to the corresponding
2163 // parameter of F.
2164 QualType ParamType = Proto->getArgType(ArgIdx);
2165 Candidate.Conversions[ArgIdx]
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002166 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redla55834a2009-04-12 17:16:29 +00002167 SuppressUserConversions, ForceRValue);
Douglas Gregord2baafd2008-10-21 16:13:35 +00002168 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002169 == ImplicitConversionSequence::BadConversion) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00002170 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002171 break;
2172 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002173 } else {
2174 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2175 // argument for which there is no corresponding parameter is
2176 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2177 Candidate.Conversions[ArgIdx].ConversionKind
2178 = ImplicitConversionSequence::EllipsisConversion;
2179 }
2180 }
2181}
2182
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002183/// \brief Add all of the function declarations in the given function set to
2184/// the overload canddiate set.
2185void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2186 Expr **Args, unsigned NumArgs,
2187 OverloadCandidateSet& CandidateSet,
2188 bool SuppressUserConversions) {
2189 for (FunctionSet::const_iterator F = Functions.begin(),
2190 FEnd = Functions.end();
Douglas Gregor993a0602009-06-27 21:05:07 +00002191 F != FEnd; ++F) {
2192 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
2193 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2194 SuppressUserConversions);
2195 else
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002196 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2197 /*FIXME: explicit args */false, 0, 0,
2198 Args, NumArgs, CandidateSet,
Douglas Gregor993a0602009-06-27 21:05:07 +00002199 SuppressUserConversions);
2200 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002201}
2202
Douglas Gregor5ed15042008-11-18 23:14:02 +00002203/// AddMethodCandidate - Adds the given C++ member function to the set
2204/// of candidate functions, using the given function call arguments
2205/// and the object argument (@c Object). For example, in a call
2206/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2207/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2208/// allow user-defined conversions via constructors or conversion
Sebastian Redla55834a2009-04-12 17:16:29 +00002209/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2210/// a slightly hacky way to implement the overloading rules for elidable copy
2211/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor5ed15042008-11-18 23:14:02 +00002212void
2213Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2214 Expr **Args, unsigned NumArgs,
2215 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002216 bool SuppressUserConversions, bool ForceRValue)
Douglas Gregor5ed15042008-11-18 23:14:02 +00002217{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002218 const FunctionProtoType* Proto
2219 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00002220 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redlbd261962009-04-16 17:51:27 +00002221 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor5ed15042008-11-18 23:14:02 +00002222 "Use AddConversionCandidate for conversion functions");
Sebastian Redlbd261962009-04-16 17:51:27 +00002223 assert(!isa<CXXConstructorDecl>(Method) &&
2224 "Use AddOverloadCandidate for constructors");
Douglas Gregor5ed15042008-11-18 23:14:02 +00002225
2226 // Add this candidate
2227 CandidateSet.push_back(OverloadCandidate());
2228 OverloadCandidate& Candidate = CandidateSet.back();
2229 Candidate.Function = Method;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002230 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002231 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002232
2233 unsigned NumArgsInProto = Proto->getNumArgs();
2234
2235 // (C++ 13.3.2p2): A candidate function having fewer than m
2236 // parameters is viable only if it has an ellipsis in its parameter
2237 // list (8.3.5).
2238 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2239 Candidate.Viable = false;
2240 return;
2241 }
2242
2243 // (C++ 13.3.2p2): A candidate function having more than m parameters
2244 // is viable only if the (m+1)st parameter has a default argument
2245 // (8.3.6). For the purposes of overload resolution, the
2246 // parameter list is truncated on the right, so that there are
2247 // exactly m parameters.
2248 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2249 if (NumArgs < MinRequiredArgs) {
2250 // Not enough arguments.
2251 Candidate.Viable = false;
2252 return;
2253 }
2254
2255 Candidate.Viable = true;
2256 Candidate.Conversions.resize(NumArgs + 1);
2257
Douglas Gregor3257fb52008-12-22 05:46:06 +00002258 if (Method->isStatic() || !Object)
2259 // The implicit object argument is ignored.
2260 Candidate.IgnoreObjectArgument = true;
2261 else {
2262 // Determine the implicit conversion sequence for the object
2263 // parameter.
2264 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2265 if (Candidate.Conversions[0].ConversionKind
2266 == ImplicitConversionSequence::BadConversion) {
2267 Candidate.Viable = false;
2268 return;
2269 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002270 }
2271
2272 // Determine the implicit conversion sequences for each of the
2273 // arguments.
2274 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2275 if (ArgIdx < NumArgsInProto) {
2276 // (C++ 13.3.2p3): for F to be a viable function, there shall
2277 // exist for each argument an implicit conversion sequence
2278 // (13.3.3.1) that converts that argument to the corresponding
2279 // parameter of F.
2280 QualType ParamType = Proto->getArgType(ArgIdx);
2281 Candidate.Conversions[ArgIdx + 1]
2282 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redla55834a2009-04-12 17:16:29 +00002283 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002284 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2285 == ImplicitConversionSequence::BadConversion) {
2286 Candidate.Viable = false;
2287 break;
2288 }
2289 } else {
2290 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2291 // argument for which there is no corresponding parameter is
2292 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2293 Candidate.Conversions[ArgIdx + 1].ConversionKind
2294 = ImplicitConversionSequence::EllipsisConversion;
2295 }
2296 }
2297}
2298
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002299/// \brief Add a C++ member function template as a candidate to the candidate
2300/// set, using template argument deduction to produce an appropriate member
2301/// function template specialization.
2302void
2303Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2304 bool HasExplicitTemplateArgs,
2305 const TemplateArgument *ExplicitTemplateArgs,
2306 unsigned NumExplicitTemplateArgs,
2307 Expr *Object, Expr **Args, unsigned NumArgs,
2308 OverloadCandidateSet& CandidateSet,
2309 bool SuppressUserConversions,
2310 bool ForceRValue) {
2311 // C++ [over.match.funcs]p7:
2312 // In each case where a candidate is a function template, candidate
2313 // function template specializations are generated using template argument
2314 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2315 // candidate functions in the usual way.113) A given name can refer to one
2316 // or more function templates and also to a set of overloaded non-template
2317 // functions. In such a case, the candidate functions generated from each
2318 // function template are combined with the set of non-template candidate
2319 // functions.
2320 TemplateDeductionInfo Info(Context);
2321 FunctionDecl *Specialization = 0;
2322 if (TemplateDeductionResult Result
2323 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2324 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2325 Args, NumArgs, Specialization, Info)) {
2326 // FIXME: Record what happened with template argument deduction, so
2327 // that we can give the user a beautiful diagnostic.
2328 (void)Result;
2329 return;
2330 }
2331
2332 // Add the function template specialization produced by template argument
2333 // deduction as a candidate.
2334 assert(Specialization && "Missing member function template specialization?");
2335 assert(isa<CXXMethodDecl>(Specialization) &&
2336 "Specialization is not a member function?");
2337 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
2338 CandidateSet, SuppressUserConversions, ForceRValue);
2339}
2340
Douglas Gregor8c860df2009-08-21 23:19:43 +00002341/// \brief Add a C++ function template specialization as a candidate
2342/// in the candidate set, using template argument deduction to produce
2343/// an appropriate function template specialization.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002344void
2345Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002346 bool HasExplicitTemplateArgs,
2347 const TemplateArgument *ExplicitTemplateArgs,
2348 unsigned NumExplicitTemplateArgs,
Douglas Gregorb60eb752009-06-25 22:08:12 +00002349 Expr **Args, unsigned NumArgs,
2350 OverloadCandidateSet& CandidateSet,
2351 bool SuppressUserConversions,
2352 bool ForceRValue) {
2353 // C++ [over.match.funcs]p7:
2354 // In each case where a candidate is a function template, candidate
2355 // function template specializations are generated using template argument
2356 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2357 // candidate functions in the usual way.113) A given name can refer to one
2358 // or more function templates and also to a set of overloaded non-template
2359 // functions. In such a case, the candidate functions generated from each
2360 // function template are combined with the set of non-template candidate
2361 // functions.
2362 TemplateDeductionInfo Info(Context);
2363 FunctionDecl *Specialization = 0;
2364 if (TemplateDeductionResult Result
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002365 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2366 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2367 Args, NumArgs, Specialization, Info)) {
Douglas Gregorb60eb752009-06-25 22:08:12 +00002368 // FIXME: Record what happened with template argument deduction, so
2369 // that we can give the user a beautiful diagnostic.
2370 (void)Result;
2371 return;
2372 }
2373
2374 // Add the function template specialization produced by template argument
2375 // deduction as a candidate.
2376 assert(Specialization && "Missing function template specialization?");
2377 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2378 SuppressUserConversions, ForceRValue);
2379}
2380
Douglas Gregor60714f92008-11-07 22:36:19 +00002381/// AddConversionCandidate - Add a C++ conversion function as a
2382/// candidate in the candidate set (C++ [over.match.conv],
2383/// C++ [over.match.copy]). From is the expression we're converting from,
2384/// and ToType is the type that we're eventually trying to convert to
2385/// (which may or may not be the same type as the type that the
2386/// conversion function produces).
2387void
2388Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2389 Expr *From, QualType ToType,
2390 OverloadCandidateSet& CandidateSet) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00002391 assert(!Conversion->getDescribedFunctionTemplate() &&
2392 "Conversion function templates use AddTemplateConversionCandidate");
2393
Douglas Gregor60714f92008-11-07 22:36:19 +00002394 // Add this candidate
2395 CandidateSet.push_back(OverloadCandidate());
2396 OverloadCandidate& Candidate = CandidateSet.back();
2397 Candidate.Function = Conversion;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002398 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002399 Candidate.IgnoreObjectArgument = false;
Douglas Gregor60714f92008-11-07 22:36:19 +00002400 Candidate.FinalConversion.setAsIdentityConversion();
2401 Candidate.FinalConversion.FromTypePtr
2402 = Conversion->getConversionType().getAsOpaquePtr();
2403 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2404
Douglas Gregor5ed15042008-11-18 23:14:02 +00002405 // Determine the implicit conversion sequence for the implicit
2406 // object parameter.
Douglas Gregor60714f92008-11-07 22:36:19 +00002407 Candidate.Viable = true;
2408 Candidate.Conversions.resize(1);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002409 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregor60714f92008-11-07 22:36:19 +00002410
Douglas Gregor60714f92008-11-07 22:36:19 +00002411 if (Candidate.Conversions[0].ConversionKind
2412 == ImplicitConversionSequence::BadConversion) {
2413 Candidate.Viable = false;
2414 return;
2415 }
2416
2417 // To determine what the conversion from the result of calling the
2418 // conversion function to the type we're eventually trying to
2419 // convert to (ToType), we need to synthesize a call to the
2420 // conversion function and attempt copy initialization from it. This
2421 // makes sure that we get the right semantics with respect to
2422 // lvalues/rvalues and the type. Fortunately, we can allocate this
2423 // call on the stack and we don't need its arguments to be
2424 // well-formed.
2425 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2426 SourceLocation());
2427 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002428 CastExpr::CK_Unknown,
Douglas Gregor70d26122008-11-12 17:17:38 +00002429 &ConversionRef, false);
Ted Kremenek362abcd2009-02-09 20:51:47 +00002430
2431 // Note that it is safe to allocate CallExpr on the stack here because
2432 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2433 // allocator).
2434 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor60714f92008-11-07 22:36:19 +00002435 Conversion->getConversionType().getNonReferenceType(),
2436 SourceLocation());
2437 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2438 switch (ICS.ConversionKind) {
2439 case ImplicitConversionSequence::StandardConversion:
2440 Candidate.FinalConversion = ICS.Standard;
2441 break;
2442
2443 case ImplicitConversionSequence::BadConversion:
2444 Candidate.Viable = false;
2445 break;
2446
2447 default:
2448 assert(false &&
2449 "Can only end up with a standard conversion sequence or failure");
2450 }
2451}
2452
Douglas Gregor8c860df2009-08-21 23:19:43 +00002453/// \brief Adds a conversion function template specialization
2454/// candidate to the overload set, using template argument deduction
2455/// to deduce the template arguments of the conversion function
2456/// template from the type that we are converting to (C++
2457/// [temp.deduct.conv]).
2458void
2459Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2460 Expr *From, QualType ToType,
2461 OverloadCandidateSet &CandidateSet) {
2462 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2463 "Only conversion function templates permitted here");
2464
2465 TemplateDeductionInfo Info(Context);
2466 CXXConversionDecl *Specialization = 0;
2467 if (TemplateDeductionResult Result
2468 = DeduceTemplateArguments(FunctionTemplate, ToType,
2469 Specialization, Info)) {
2470 // FIXME: Record what happened with template argument deduction, so
2471 // that we can give the user a beautiful diagnostic.
2472 (void)Result;
2473 return;
2474 }
2475
2476 // Add the conversion function template specialization produced by
2477 // template argument deduction as a candidate.
2478 assert(Specialization && "Missing function template specialization?");
2479 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2480}
2481
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002482/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2483/// converts the given @c Object to a function pointer via the
2484/// conversion function @c Conversion, and then attempts to call it
2485/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2486/// the type of function that we'll eventually be calling.
2487void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002488 const FunctionProtoType *Proto,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002489 Expr *Object, Expr **Args, unsigned NumArgs,
2490 OverloadCandidateSet& CandidateSet) {
2491 CandidateSet.push_back(OverloadCandidate());
2492 OverloadCandidate& Candidate = CandidateSet.back();
2493 Candidate.Function = 0;
2494 Candidate.Surrogate = Conversion;
2495 Candidate.Viable = true;
2496 Candidate.IsSurrogate = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002497 Candidate.IgnoreObjectArgument = false;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002498 Candidate.Conversions.resize(NumArgs + 1);
2499
2500 // Determine the implicit conversion sequence for the implicit
2501 // object parameter.
2502 ImplicitConversionSequence ObjectInit
2503 = TryObjectArgumentInitialization(Object, Conversion);
2504 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2505 Candidate.Viable = false;
2506 return;
2507 }
2508
2509 // The first conversion is actually a user-defined conversion whose
2510 // first conversion is ObjectInit's standard conversion (which is
2511 // effectively a reference binding). Record it as such.
2512 Candidate.Conversions[0].ConversionKind
2513 = ImplicitConversionSequence::UserDefinedConversion;
2514 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2515 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2516 Candidate.Conversions[0].UserDefined.After
2517 = Candidate.Conversions[0].UserDefined.Before;
2518 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2519
2520 // Find the
2521 unsigned NumArgsInProto = Proto->getNumArgs();
2522
2523 // (C++ 13.3.2p2): A candidate function having fewer than m
2524 // parameters is viable only if it has an ellipsis in its parameter
2525 // list (8.3.5).
2526 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2527 Candidate.Viable = false;
2528 return;
2529 }
2530
2531 // Function types don't have any default arguments, so just check if
2532 // we have enough arguments.
2533 if (NumArgs < NumArgsInProto) {
2534 // Not enough arguments.
2535 Candidate.Viable = false;
2536 return;
2537 }
2538
2539 // Determine the implicit conversion sequences for each of the
2540 // arguments.
2541 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2542 if (ArgIdx < NumArgsInProto) {
2543 // (C++ 13.3.2p3): for F to be a viable function, there shall
2544 // exist for each argument an implicit conversion sequence
2545 // (13.3.3.1) that converts that argument to the corresponding
2546 // parameter of F.
2547 QualType ParamType = Proto->getArgType(ArgIdx);
2548 Candidate.Conversions[ArgIdx + 1]
2549 = TryCopyInitialization(Args[ArgIdx], ParamType,
2550 /*SuppressUserConversions=*/false);
2551 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2552 == ImplicitConversionSequence::BadConversion) {
2553 Candidate.Viable = false;
2554 break;
2555 }
2556 } else {
2557 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2558 // argument for which there is no corresponding parameter is
2559 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2560 Candidate.Conversions[ArgIdx + 1].ConversionKind
2561 = ImplicitConversionSequence::EllipsisConversion;
2562 }
2563 }
2564}
2565
Mike Stumpe127ae32009-05-16 07:39:55 +00002566// FIXME: This will eventually be removed, once we've migrated all of the
2567// operator overloading logic over to the scheme used by binary operators, which
2568// works for template instantiation.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002569void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor48a87322009-02-04 16:44:47 +00002570 SourceLocation OpLoc,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002571 Expr **Args, unsigned NumArgs,
Douglas Gregor48a87322009-02-04 16:44:47 +00002572 OverloadCandidateSet& CandidateSet,
2573 SourceRange OpRange) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002574
2575 FunctionSet Functions;
2576
2577 QualType T1 = Args[0]->getType();
2578 QualType T2;
2579 if (NumArgs > 1)
2580 T2 = Args[1]->getType();
2581
2582 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregorde72f3e2009-05-19 00:01:19 +00002583 if (S)
2584 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002585 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2586 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2587 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2588 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2589}
2590
2591/// \brief Add overload candidates for overloaded operators that are
2592/// member functions.
2593///
2594/// Add the overloaded operator candidates that are member functions
2595/// for the operator Op that was used in an operator expression such
2596/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2597/// CandidateSet will store the added overload candidates. (C++
2598/// [over.match.oper]).
2599void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2600 SourceLocation OpLoc,
2601 Expr **Args, unsigned NumArgs,
2602 OverloadCandidateSet& CandidateSet,
2603 SourceRange OpRange) {
Douglas Gregor5ed15042008-11-18 23:14:02 +00002604 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2605
2606 // C++ [over.match.oper]p3:
2607 // For a unary operator @ with an operand of a type whose
2608 // cv-unqualified version is T1, and for a binary operator @ with
2609 // a left operand of a type whose cv-unqualified version is T1 and
2610 // a right operand of a type whose cv-unqualified version is T2,
2611 // three sets of candidate functions, designated member
2612 // candidates, non-member candidates and built-in candidates, are
2613 // constructed as follows:
2614 QualType T1 = Args[0]->getType();
2615 QualType T2;
2616 if (NumArgs > 1)
2617 T2 = Args[1]->getType();
2618
2619 // -- If T1 is a class type, the set of member candidates is the
2620 // result of the qualified lookup of T1::operator@
2621 // (13.3.1.1.1); otherwise, the set of member candidates is
2622 // empty.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002623 // FIXME: Lookup in base classes, too!
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002624 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002625 DeclContext::lookup_const_iterator Oper, OperEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002626 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002627 Oper != OperEnd; ++Oper)
2628 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2629 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002630 /*SuppressUserConversions=*/false);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002631 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002632}
2633
Douglas Gregor70d26122008-11-12 17:17:38 +00002634/// AddBuiltinCandidate - Add a candidate for a built-in
2635/// operator. ResultTy and ParamTys are the result and parameter types
2636/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorab141112009-01-13 00:52:54 +00002637/// arguments being passed to the candidate. IsAssignmentOperator
2638/// should be true when this built-in candidate is an assignment
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002639/// operator. NumContextualBoolArguments is the number of arguments
2640/// (at the beginning of the argument list) that will be contextually
2641/// converted to bool.
Douglas Gregor70d26122008-11-12 17:17:38 +00002642void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2643 Expr **Args, unsigned NumArgs,
Douglas Gregorab141112009-01-13 00:52:54 +00002644 OverloadCandidateSet& CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002645 bool IsAssignmentOperator,
2646 unsigned NumContextualBoolArguments) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002647 // Add this candidate
2648 CandidateSet.push_back(OverloadCandidate());
2649 OverloadCandidate& Candidate = CandidateSet.back();
2650 Candidate.Function = 0;
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00002651 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002652 Candidate.IgnoreObjectArgument = false;
Douglas Gregor70d26122008-11-12 17:17:38 +00002653 Candidate.BuiltinTypes.ResultTy = ResultTy;
2654 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2655 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2656
2657 // Determine the implicit conversion sequences for each of the
2658 // arguments.
2659 Candidate.Viable = true;
2660 Candidate.Conversions.resize(NumArgs);
2661 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorab141112009-01-13 00:52:54 +00002662 // C++ [over.match.oper]p4:
2663 // For the built-in assignment operators, conversions of the
2664 // left operand are restricted as follows:
2665 // -- no temporaries are introduced to hold the left operand, and
2666 // -- no user-defined conversions are applied to the left
2667 // operand to achieve a type match with the left-most
2668 // parameter of a built-in candidate.
2669 //
2670 // We block these conversions by turning off user-defined
2671 // conversions, since that is the only way that initialization of
2672 // a reference to a non-class type can occur from something that
2673 // is not of the same type.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002674 if (ArgIdx < NumContextualBoolArguments) {
2675 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2676 "Contextual conversion to bool requires bool type");
2677 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2678 } else {
2679 Candidate.Conversions[ArgIdx]
2680 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2681 ArgIdx == 0 && IsAssignmentOperator);
2682 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002683 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002684 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002685 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002686 break;
2687 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002688 }
2689}
2690
2691/// BuiltinCandidateTypeSet - A set of types that will be used for the
2692/// candidate operator functions for built-in operators (C++
2693/// [over.built]). The types are separated into pointer types and
2694/// enumeration types.
2695class BuiltinCandidateTypeSet {
2696 /// TypeSet - A set of types.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002697 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregor70d26122008-11-12 17:17:38 +00002698
2699 /// PointerTypes - The set of pointer types that will be used in the
2700 /// built-in candidates.
2701 TypeSet PointerTypes;
2702
Sebastian Redl674d1b72009-04-19 21:53:20 +00002703 /// MemberPointerTypes - The set of member pointer types that will be
2704 /// used in the built-in candidates.
2705 TypeSet MemberPointerTypes;
2706
Douglas Gregor70d26122008-11-12 17:17:38 +00002707 /// EnumerationTypes - The set of enumeration types that will be
2708 /// used in the built-in candidates.
2709 TypeSet EnumerationTypes;
2710
Douglas Gregorb35c7992009-08-24 15:23:48 +00002711 /// Sema - The semantic analysis instance where we are building the
2712 /// candidate type set.
2713 Sema &SemaRef;
2714
Douglas Gregor70d26122008-11-12 17:17:38 +00002715 /// Context - The AST context in which we will build the type sets.
2716 ASTContext &Context;
2717
Sebastian Redl674d1b72009-04-19 21:53:20 +00002718 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2719 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002720
2721public:
2722 /// iterator - Iterates through the types that are part of the set.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002723 typedef TypeSet::iterator iterator;
Douglas Gregor70d26122008-11-12 17:17:38 +00002724
Douglas Gregorb35c7992009-08-24 15:23:48 +00002725 BuiltinCandidateTypeSet(Sema &SemaRef)
2726 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregor70d26122008-11-12 17:17:38 +00002727
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002728 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2729 bool AllowExplicitConversions);
Douglas Gregor70d26122008-11-12 17:17:38 +00002730
2731 /// pointer_begin - First pointer type found;
2732 iterator pointer_begin() { return PointerTypes.begin(); }
2733
Sebastian Redl674d1b72009-04-19 21:53:20 +00002734 /// pointer_end - Past the last pointer type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002735 iterator pointer_end() { return PointerTypes.end(); }
2736
Sebastian Redl674d1b72009-04-19 21:53:20 +00002737 /// member_pointer_begin - First member pointer type found;
2738 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2739
2740 /// member_pointer_end - Past the last member pointer type found;
2741 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2742
Douglas Gregor70d26122008-11-12 17:17:38 +00002743 /// enumeration_begin - First enumeration type found;
2744 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2745
Sebastian Redl674d1b72009-04-19 21:53:20 +00002746 /// enumeration_end - Past the last enumeration type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002747 iterator enumeration_end() { return EnumerationTypes.end(); }
2748};
2749
Sebastian Redl674d1b72009-04-19 21:53:20 +00002750/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregor70d26122008-11-12 17:17:38 +00002751/// the set of pointer types along with any more-qualified variants of
2752/// that type. For example, if @p Ty is "int const *", this routine
2753/// will add "int const *", "int const volatile *", "int const
2754/// restrict *", and "int const volatile restrict *" to the set of
2755/// pointer types. Returns true if the add of @p Ty itself succeeded,
2756/// false otherwise.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002757bool
2758BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002759 // Insert this type.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002760 if (!PointerTypes.insert(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002761 return false;
2762
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002763 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002764 QualType PointeeTy = PointerTy->getPointeeType();
2765 // FIXME: Optimize this so that we don't keep trying to add the same types.
2766
Mike Stumpe127ae32009-05-16 07:39:55 +00002767 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2768 // pointer conversions that don't cast away constness?
Douglas Gregor70d26122008-11-12 17:17:38 +00002769 if (!PointeeTy.isConstQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002770 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002771 (Context.getPointerType(PointeeTy.withConst()));
2772 if (!PointeeTy.isVolatileQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002773 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002774 (Context.getPointerType(PointeeTy.withVolatile()));
2775 if (!PointeeTy.isRestrictQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002776 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002777 (Context.getPointerType(PointeeTy.withRestrict()));
2778 }
2779
2780 return true;
2781}
2782
Sebastian Redl674d1b72009-04-19 21:53:20 +00002783/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2784/// to the set of pointer types along with any more-qualified variants of
2785/// that type. For example, if @p Ty is "int const *", this routine
2786/// will add "int const *", "int const volatile *", "int const
2787/// restrict *", and "int const volatile restrict *" to the set of
2788/// pointer types. Returns true if the add of @p Ty itself succeeded,
2789/// false otherwise.
2790bool
2791BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2792 QualType Ty) {
2793 // Insert this type.
2794 if (!MemberPointerTypes.insert(Ty))
2795 return false;
2796
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002797 if (const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>()) {
Sebastian Redl674d1b72009-04-19 21:53:20 +00002798 QualType PointeeTy = PointerTy->getPointeeType();
2799 const Type *ClassTy = PointerTy->getClass();
2800 // FIXME: Optimize this so that we don't keep trying to add the same types.
2801
2802 if (!PointeeTy.isConstQualified())
2803 AddMemberPointerWithMoreQualifiedTypeVariants
2804 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2805 if (!PointeeTy.isVolatileQualified())
2806 AddMemberPointerWithMoreQualifiedTypeVariants
2807 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2808 if (!PointeeTy.isRestrictQualified())
2809 AddMemberPointerWithMoreQualifiedTypeVariants
2810 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2811 }
2812
2813 return true;
2814}
2815
Douglas Gregor70d26122008-11-12 17:17:38 +00002816/// AddTypesConvertedFrom - Add each of the types to which the type @p
2817/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl674d1b72009-04-19 21:53:20 +00002818/// primarily interested in pointer types and enumeration types. We also
2819/// take member pointer types, for the conditional operator.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002820/// AllowUserConversions is true if we should look at the conversion
2821/// functions of a class type, and AllowExplicitConversions if we
2822/// should also include the explicit conversion functions of a class
2823/// type.
2824void
2825BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2826 bool AllowUserConversions,
2827 bool AllowExplicitConversions) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002828 // Only deal with canonical types.
2829 Ty = Context.getCanonicalType(Ty);
2830
2831 // Look through reference types; they aren't part of the type of an
2832 // expression for the purposes of conversions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002833 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregor70d26122008-11-12 17:17:38 +00002834 Ty = RefTy->getPointeeType();
2835
2836 // We don't care about qualifiers on the type.
2837 Ty = Ty.getUnqualifiedType();
2838
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002839 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002840 QualType PointeeTy = PointerTy->getPointeeType();
2841
2842 // Insert our type, and its more-qualified variants, into the set
2843 // of types.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002844 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002845 return;
2846
2847 // Add 'cv void*' to our set of types.
2848 if (!Ty->isVoidType()) {
2849 QualType QualVoid
2850 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl674d1b72009-04-19 21:53:20 +00002851 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregor70d26122008-11-12 17:17:38 +00002852 }
2853
2854 // If this is a pointer to a class type, add pointers to its bases
2855 // (with the same level of cv-qualification as the original
2856 // derived class, of course).
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002857 if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002858 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2859 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2860 Base != ClassDecl->bases_end(); ++Base) {
2861 QualType BaseTy = Context.getCanonicalType(Base->getType());
2862 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2863
2864 // Add the pointer type, recursively, so that we get all of
2865 // the indirect base classes, too.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002866 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002867 }
2868 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00002869 } else if (Ty->isMemberPointerType()) {
2870 // Member pointers are far easier, since the pointee can't be converted.
2871 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2872 return;
Douglas Gregor70d26122008-11-12 17:17:38 +00002873 } else if (Ty->isEnumeralType()) {
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002874 EnumerationTypes.insert(Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002875 } else if (AllowUserConversions) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002876 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorb35c7992009-08-24 15:23:48 +00002877 if (SemaRef.RequireCompleteType(SourceLocation(), Ty, 0)) {
2878 // No conversion functions in incomplete types.
2879 return;
2880 }
2881
Douglas Gregor70d26122008-11-12 17:17:38 +00002882 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2883 // FIXME: Visit conversion functions in the base classes, too.
2884 OverloadedFunctionDecl *Conversions
2885 = ClassDecl->getConversionFunctions();
2886 for (OverloadedFunctionDecl::function_iterator Func
2887 = Conversions->function_begin();
2888 Func != Conversions->function_end(); ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00002889 CXXConversionDecl *Conv;
2890 FunctionTemplateDecl *ConvTemplate;
2891 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
2892
2893 // Skip conversion function templates; they don't tell us anything
2894 // about which builtin types we can convert to.
2895 if (ConvTemplate)
2896 continue;
2897
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002898 if (AllowExplicitConversions || !Conv->isExplicit())
2899 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002900 }
2901 }
2902 }
2903}
2904
Douglas Gregor9a375942009-08-24 13:43:27 +00002905/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
2906/// the volatile- and non-volatile-qualified assignment operators for the
2907/// given type to the candidate set.
2908static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
2909 QualType T,
2910 Expr **Args,
2911 unsigned NumArgs,
2912 OverloadCandidateSet &CandidateSet) {
2913 QualType ParamTypes[2];
2914
2915 // T& operator=(T&, T)
2916 ParamTypes[0] = S.Context.getLValueReferenceType(T);
2917 ParamTypes[1] = T;
2918 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2919 /*IsAssignmentOperator=*/true);
2920
2921 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
2922 // volatile T& operator=(volatile T&, T)
2923 ParamTypes[0] = S.Context.getLValueReferenceType(T.withVolatile());
2924 ParamTypes[1] = T;
2925 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2926 /*IsAssignmentOperator=*/true);
2927 }
2928}
2929
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002930/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2931/// operator overloads to the candidate set (C++ [over.built]), based
2932/// on the operator @p Op and the arguments given. For example, if the
2933/// operator is a binary '+', this routine might add "int
2934/// operator+(int, int)" to cover integer addition.
Douglas Gregor70d26122008-11-12 17:17:38 +00002935void
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002936Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2937 Expr **Args, unsigned NumArgs,
2938 OverloadCandidateSet& CandidateSet) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002939 // The set of "promoted arithmetic types", which are the arithmetic
2940 // types are that preserved by promotion (C++ [over.built]p2). Note
2941 // that the first few of these types are the promoted integral
2942 // types; these types need to be first.
2943 // FIXME: What about complex?
2944 const unsigned FirstIntegralType = 0;
2945 const unsigned LastIntegralType = 13;
2946 const unsigned FirstPromotedIntegralType = 7,
2947 LastPromotedIntegralType = 13;
2948 const unsigned FirstPromotedArithmeticType = 7,
2949 LastPromotedArithmeticType = 16;
2950 const unsigned NumArithmeticTypes = 16;
2951 QualType ArithmeticTypes[NumArithmeticTypes] = {
Alisdair Meredith2bcacb62009-07-14 06:30:34 +00002952 Context.BoolTy, Context.CharTy, Context.WCharTy,
Douglas Gregor9a375942009-08-24 13:43:27 +00002953// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregor70d26122008-11-12 17:17:38 +00002954 Context.SignedCharTy, Context.ShortTy,
2955 Context.UnsignedCharTy, Context.UnsignedShortTy,
2956 Context.IntTy, Context.LongTy, Context.LongLongTy,
2957 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2958 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2959 };
2960
2961 // Find all of the types that the arguments can convert to, but only
2962 // if the operator we're looking at has built-in operator candidates
2963 // that make use of these types.
Douglas Gregorb35c7992009-08-24 15:23:48 +00002964 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregor70d26122008-11-12 17:17:38 +00002965 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2966 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002967 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregor70d26122008-11-12 17:17:38 +00002968 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002969 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redlbd261962009-04-16 17:51:27 +00002970 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002971 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002972 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2973 true,
2974 (Op == OO_Exclaim ||
2975 Op == OO_AmpAmp ||
2976 Op == OO_PipePipe));
Douglas Gregor70d26122008-11-12 17:17:38 +00002977 }
2978
2979 bool isComparison = false;
2980 switch (Op) {
2981 case OO_None:
2982 case NUM_OVERLOADED_OPERATORS:
2983 assert(false && "Expected an overloaded operator");
2984 break;
2985
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002986 case OO_Star: // '*' is either unary or binary
2987 if (NumArgs == 1)
2988 goto UnaryStar;
2989 else
2990 goto BinaryStar;
2991 break;
2992
2993 case OO_Plus: // '+' is either unary or binary
2994 if (NumArgs == 1)
2995 goto UnaryPlus;
2996 else
2997 goto BinaryPlus;
2998 break;
2999
3000 case OO_Minus: // '-' is either unary or binary
3001 if (NumArgs == 1)
3002 goto UnaryMinus;
3003 else
3004 goto BinaryMinus;
3005 break;
3006
3007 case OO_Amp: // '&' is either unary or binary
3008 if (NumArgs == 1)
3009 goto UnaryAmp;
3010 else
3011 goto BinaryAmp;
3012
3013 case OO_PlusPlus:
3014 case OO_MinusMinus:
3015 // C++ [over.built]p3:
3016 //
3017 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3018 // is either volatile or empty, there exist candidate operator
3019 // functions of the form
3020 //
3021 // VQ T& operator++(VQ T&);
3022 // T operator++(VQ T&, int);
3023 //
3024 // C++ [over.built]p4:
3025 //
3026 // For every pair (T, VQ), where T is an arithmetic type other
3027 // than bool, and VQ is either volatile or empty, there exist
3028 // candidate operator functions of the form
3029 //
3030 // VQ T& operator--(VQ T&);
3031 // T operator--(VQ T&, int);
3032 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
3033 Arith < NumArithmeticTypes; ++Arith) {
3034 QualType ArithTy = ArithmeticTypes[Arith];
3035 QualType ParamTypes[2]
Sebastian Redlce6fff02009-03-16 23:22:08 +00003036 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003037
3038 // Non-volatile version.
3039 if (NumArgs == 1)
3040 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3041 else
3042 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3043
3044 // Volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003045 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003046 if (NumArgs == 1)
3047 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3048 else
3049 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3050 }
3051
3052 // C++ [over.built]p5:
3053 //
3054 // For every pair (T, VQ), where T is a cv-qualified or
3055 // cv-unqualified object type, and VQ is either volatile or
3056 // empty, there exist candidate operator functions of the form
3057 //
3058 // T*VQ& operator++(T*VQ&);
3059 // T*VQ& operator--(T*VQ&);
3060 // T* operator++(T*VQ&, int);
3061 // T* operator--(T*VQ&, int);
3062 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3063 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3064 // Skip pointer types that aren't pointers to object types.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003065 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003066 continue;
3067
3068 QualType ParamTypes[2] = {
Sebastian Redlce6fff02009-03-16 23:22:08 +00003069 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003070 };
3071
3072 // Without volatile
3073 if (NumArgs == 1)
3074 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3075 else
3076 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3077
3078 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3079 // With volatile
Sebastian Redlce6fff02009-03-16 23:22:08 +00003080 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003081 if (NumArgs == 1)
3082 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3083 else
3084 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3085 }
3086 }
3087 break;
3088
3089 UnaryStar:
3090 // C++ [over.built]p6:
3091 // For every cv-qualified or cv-unqualified object type T, there
3092 // exist candidate operator functions of the form
3093 //
3094 // T& operator*(T*);
3095 //
3096 // C++ [over.built]p7:
3097 // For every function type T, there exist candidate operator
3098 // functions of the form
3099 // T& operator*(T*);
3100 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3101 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3102 QualType ParamTy = *Ptr;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003103 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003104 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003105 &ParamTy, Args, 1, CandidateSet);
3106 }
3107 break;
3108
3109 UnaryPlus:
3110 // C++ [over.built]p8:
3111 // For every type T, there exist candidate operator functions of
3112 // the form
3113 //
3114 // T* operator+(T*);
3115 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3116 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3117 QualType ParamTy = *Ptr;
3118 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3119 }
3120
3121 // Fall through
3122
3123 UnaryMinus:
3124 // C++ [over.built]p9:
3125 // For every promoted arithmetic type T, there exist candidate
3126 // operator functions of the form
3127 //
3128 // T operator+(T);
3129 // T operator-(T);
3130 for (unsigned Arith = FirstPromotedArithmeticType;
3131 Arith < LastPromotedArithmeticType; ++Arith) {
3132 QualType ArithTy = ArithmeticTypes[Arith];
3133 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3134 }
3135 break;
3136
3137 case OO_Tilde:
3138 // C++ [over.built]p10:
3139 // For every promoted integral type T, there exist candidate
3140 // operator functions of the form
3141 //
3142 // T operator~(T);
3143 for (unsigned Int = FirstPromotedIntegralType;
3144 Int < LastPromotedIntegralType; ++Int) {
3145 QualType IntTy = ArithmeticTypes[Int];
3146 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3147 }
3148 break;
3149
Douglas Gregor70d26122008-11-12 17:17:38 +00003150 case OO_New:
3151 case OO_Delete:
3152 case OO_Array_New:
3153 case OO_Array_Delete:
Douglas Gregor70d26122008-11-12 17:17:38 +00003154 case OO_Call:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003155 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregor70d26122008-11-12 17:17:38 +00003156 break;
3157
3158 case OO_Comma:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003159 UnaryAmp:
3160 case OO_Arrow:
Douglas Gregor70d26122008-11-12 17:17:38 +00003161 // C++ [over.match.oper]p3:
3162 // -- For the operator ',', the unary operator '&', or the
3163 // operator '->', the built-in candidates set is empty.
Douglas Gregor70d26122008-11-12 17:17:38 +00003164 break;
3165
Douglas Gregor9a375942009-08-24 13:43:27 +00003166 case OO_EqualEqual:
3167 case OO_ExclaimEqual:
3168 // C++ [over.match.oper]p16:
3169 // For every pointer to member type T, there exist candidate operator
3170 // functions of the form
3171 //
3172 // bool operator==(T,T);
3173 // bool operator!=(T,T);
3174 for (BuiltinCandidateTypeSet::iterator
3175 MemPtr = CandidateTypes.member_pointer_begin(),
3176 MemPtrEnd = CandidateTypes.member_pointer_end();
3177 MemPtr != MemPtrEnd;
3178 ++MemPtr) {
3179 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3180 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3181 }
3182
3183 // Fall through
3184
Douglas Gregor70d26122008-11-12 17:17:38 +00003185 case OO_Less:
3186 case OO_Greater:
3187 case OO_LessEqual:
3188 case OO_GreaterEqual:
Douglas Gregor70d26122008-11-12 17:17:38 +00003189 // C++ [over.built]p15:
3190 //
3191 // For every pointer or enumeration type T, there exist
3192 // candidate operator functions of the form
3193 //
3194 // bool operator<(T, T);
3195 // bool operator>(T, T);
3196 // bool operator<=(T, T);
3197 // bool operator>=(T, T);
3198 // bool operator==(T, T);
3199 // bool operator!=(T, T);
3200 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3201 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3202 QualType ParamTypes[2] = { *Ptr, *Ptr };
3203 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3204 }
3205 for (BuiltinCandidateTypeSet::iterator Enum
3206 = CandidateTypes.enumeration_begin();
3207 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3208 QualType ParamTypes[2] = { *Enum, *Enum };
3209 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3210 }
3211
3212 // Fall through.
3213 isComparison = true;
3214
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003215 BinaryPlus:
3216 BinaryMinus:
Douglas Gregor70d26122008-11-12 17:17:38 +00003217 if (!isComparison) {
3218 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3219
3220 // C++ [over.built]p13:
3221 //
3222 // For every cv-qualified or cv-unqualified object type T
3223 // there exist candidate operator functions of the form
3224 //
3225 // T* operator+(T*, ptrdiff_t);
3226 // T& operator[](T*, ptrdiff_t); [BELOW]
3227 // T* operator-(T*, ptrdiff_t);
3228 // T* operator+(ptrdiff_t, T*);
3229 // T& operator[](ptrdiff_t, T*); [BELOW]
3230 //
3231 // C++ [over.built]p14:
3232 //
3233 // For every T, where T is a pointer to object type, there
3234 // exist candidate operator functions of the form
3235 //
3236 // ptrdiff_t operator-(T, T);
3237 for (BuiltinCandidateTypeSet::iterator Ptr
3238 = CandidateTypes.pointer_begin();
3239 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3240 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3241
3242 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3243 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3244
3245 if (Op == OO_Plus) {
3246 // T* operator+(ptrdiff_t, T*);
3247 ParamTypes[0] = ParamTypes[1];
3248 ParamTypes[1] = *Ptr;
3249 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3250 } else {
3251 // ptrdiff_t operator-(T, T);
3252 ParamTypes[1] = *Ptr;
3253 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3254 Args, 2, CandidateSet);
3255 }
3256 }
3257 }
3258 // Fall through
3259
Douglas Gregor70d26122008-11-12 17:17:38 +00003260 case OO_Slash:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003261 BinaryStar:
Sebastian Redlbd261962009-04-16 17:51:27 +00003262 Conditional:
Douglas Gregor70d26122008-11-12 17:17:38 +00003263 // C++ [over.built]p12:
3264 //
3265 // For every pair of promoted arithmetic types L and R, there
3266 // exist candidate operator functions of the form
3267 //
3268 // LR operator*(L, R);
3269 // LR operator/(L, R);
3270 // LR operator+(L, R);
3271 // LR operator-(L, R);
3272 // bool operator<(L, R);
3273 // bool operator>(L, R);
3274 // bool operator<=(L, R);
3275 // bool operator>=(L, R);
3276 // bool operator==(L, R);
3277 // bool operator!=(L, R);
3278 //
3279 // where LR is the result of the usual arithmetic conversions
3280 // between types L and R.
Sebastian Redlbd261962009-04-16 17:51:27 +00003281 //
3282 // C++ [over.built]p24:
3283 //
3284 // For every pair of promoted arithmetic types L and R, there exist
3285 // candidate operator functions of the form
3286 //
3287 // LR operator?(bool, L, R);
3288 //
3289 // where LR is the result of the usual arithmetic conversions
3290 // between types L and R.
3291 // Our candidates ignore the first parameter.
Douglas Gregor70d26122008-11-12 17:17:38 +00003292 for (unsigned Left = FirstPromotedArithmeticType;
3293 Left < LastPromotedArithmeticType; ++Left) {
3294 for (unsigned Right = FirstPromotedArithmeticType;
3295 Right < LastPromotedArithmeticType; ++Right) {
3296 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman6ae7d112009-08-19 07:44:53 +00003297 QualType Result
3298 = isComparison
3299 ? Context.BoolTy
3300 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003301 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3302 }
3303 }
3304 break;
3305
3306 case OO_Percent:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003307 BinaryAmp:
Douglas Gregor70d26122008-11-12 17:17:38 +00003308 case OO_Caret:
3309 case OO_Pipe:
3310 case OO_LessLess:
3311 case OO_GreaterGreater:
3312 // C++ [over.built]p17:
3313 //
3314 // For every pair of promoted integral types L and R, there
3315 // exist candidate operator functions of the form
3316 //
3317 // LR operator%(L, R);
3318 // LR operator&(L, R);
3319 // LR operator^(L, R);
3320 // LR operator|(L, R);
3321 // L operator<<(L, R);
3322 // L operator>>(L, R);
3323 //
3324 // where LR is the result of the usual arithmetic conversions
3325 // between types L and R.
3326 for (unsigned Left = FirstPromotedIntegralType;
3327 Left < LastPromotedIntegralType; ++Left) {
3328 for (unsigned Right = FirstPromotedIntegralType;
3329 Right < LastPromotedIntegralType; ++Right) {
3330 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3331 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3332 ? LandR[0]
Eli Friedman6ae7d112009-08-19 07:44:53 +00003333 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003334 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3335 }
3336 }
3337 break;
3338
3339 case OO_Equal:
3340 // C++ [over.built]p20:
3341 //
3342 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor9a375942009-08-24 13:43:27 +00003343 // pointer to member type and VQ is either volatile or
Douglas Gregor70d26122008-11-12 17:17:38 +00003344 // empty, there exist candidate operator functions of the form
3345 //
3346 // VQ T& operator=(VQ T&, T);
Douglas Gregor9a375942009-08-24 13:43:27 +00003347 for (BuiltinCandidateTypeSet::iterator
3348 Enum = CandidateTypes.enumeration_begin(),
3349 EnumEnd = CandidateTypes.enumeration_end();
3350 Enum != EnumEnd; ++Enum)
3351 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
3352 CandidateSet);
3353 for (BuiltinCandidateTypeSet::iterator
3354 MemPtr = CandidateTypes.member_pointer_begin(),
3355 MemPtrEnd = CandidateTypes.member_pointer_end();
3356 MemPtr != MemPtrEnd; ++MemPtr)
3357 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
3358 CandidateSet);
3359 // Fall through.
Douglas Gregor70d26122008-11-12 17:17:38 +00003360
3361 case OO_PlusEqual:
3362 case OO_MinusEqual:
3363 // C++ [over.built]p19:
3364 //
3365 // For every pair (T, VQ), where T is any type and VQ is either
3366 // volatile or empty, there exist candidate operator functions
3367 // of the form
3368 //
3369 // T*VQ& operator=(T*VQ&, T*);
3370 //
3371 // C++ [over.built]p21:
3372 //
3373 // For every pair (T, VQ), where T is a cv-qualified or
3374 // cv-unqualified object type and VQ is either volatile or
3375 // empty, there exist candidate operator functions of the form
3376 //
3377 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3378 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3379 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3380 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3381 QualType ParamTypes[2];
3382 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3383
3384 // non-volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003385 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorab141112009-01-13 00:52:54 +00003386 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3387 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003388
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003389 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3390 // volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003391 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregorab141112009-01-13 00:52:54 +00003392 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3393 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003394 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003395 }
3396 // Fall through.
3397
3398 case OO_StarEqual:
3399 case OO_SlashEqual:
3400 // C++ [over.built]p18:
3401 //
3402 // For every triple (L, VQ, R), where L is an arithmetic type,
3403 // VQ is either volatile or empty, and R is a promoted
3404 // arithmetic type, there exist candidate operator functions of
3405 // the form
3406 //
3407 // VQ L& operator=(VQ L&, R);
3408 // VQ L& operator*=(VQ L&, R);
3409 // VQ L& operator/=(VQ L&, R);
3410 // VQ L& operator+=(VQ L&, R);
3411 // VQ L& operator-=(VQ L&, R);
3412 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3413 for (unsigned Right = FirstPromotedArithmeticType;
3414 Right < LastPromotedArithmeticType; ++Right) {
3415 QualType ParamTypes[2];
3416 ParamTypes[1] = ArithmeticTypes[Right];
3417
3418 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003419 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorab141112009-01-13 00:52:54 +00003420 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3421 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003422
3423 // Add this built-in operator as a candidate (VQ is 'volatile').
3424 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003425 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorab141112009-01-13 00:52:54 +00003426 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3427 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003428 }
3429 }
3430 break;
3431
3432 case OO_PercentEqual:
3433 case OO_LessLessEqual:
3434 case OO_GreaterGreaterEqual:
3435 case OO_AmpEqual:
3436 case OO_CaretEqual:
3437 case OO_PipeEqual:
3438 // C++ [over.built]p22:
3439 //
3440 // For every triple (L, VQ, R), where L is an integral type, VQ
3441 // is either volatile or empty, and R is a promoted integral
3442 // type, there exist candidate operator functions of the form
3443 //
3444 // VQ L& operator%=(VQ L&, R);
3445 // VQ L& operator<<=(VQ L&, R);
3446 // VQ L& operator>>=(VQ L&, R);
3447 // VQ L& operator&=(VQ L&, R);
3448 // VQ L& operator^=(VQ L&, R);
3449 // VQ L& operator|=(VQ L&, R);
3450 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3451 for (unsigned Right = FirstPromotedIntegralType;
3452 Right < LastPromotedIntegralType; ++Right) {
3453 QualType ParamTypes[2];
3454 ParamTypes[1] = ArithmeticTypes[Right];
3455
3456 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003457 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003458 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3459
3460 // Add this built-in operator as a candidate (VQ is 'volatile').
3461 ParamTypes[0] = ArithmeticTypes[Left];
3462 ParamTypes[0].addVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003463 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003464 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3465 }
3466 }
3467 break;
3468
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003469 case OO_Exclaim: {
3470 // C++ [over.operator]p23:
3471 //
3472 // There also exist candidate operator functions of the form
3473 //
3474 // bool operator!(bool);
3475 // bool operator&&(bool, bool); [BELOW]
3476 // bool operator||(bool, bool); [BELOW]
3477 QualType ParamTy = Context.BoolTy;
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003478 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3479 /*IsAssignmentOperator=*/false,
3480 /*NumContextualBoolArguments=*/1);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003481 break;
3482 }
3483
Douglas Gregor70d26122008-11-12 17:17:38 +00003484 case OO_AmpAmp:
3485 case OO_PipePipe: {
3486 // C++ [over.operator]p23:
3487 //
3488 // There also exist candidate operator functions of the form
3489 //
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003490 // bool operator!(bool); [ABOVE]
Douglas Gregor70d26122008-11-12 17:17:38 +00003491 // bool operator&&(bool, bool);
3492 // bool operator||(bool, bool);
3493 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003494 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3495 /*IsAssignmentOperator=*/false,
3496 /*NumContextualBoolArguments=*/2);
Douglas Gregor70d26122008-11-12 17:17:38 +00003497 break;
3498 }
3499
3500 case OO_Subscript:
3501 // C++ [over.built]p13:
3502 //
3503 // For every cv-qualified or cv-unqualified object type T there
3504 // exist candidate operator functions of the form
3505 //
3506 // T* operator+(T*, ptrdiff_t); [ABOVE]
3507 // T& operator[](T*, ptrdiff_t);
3508 // T* operator-(T*, ptrdiff_t); [ABOVE]
3509 // T* operator+(ptrdiff_t, T*); [ABOVE]
3510 // T& operator[](ptrdiff_t, T*);
3511 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3512 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3513 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003514 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003515 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregor70d26122008-11-12 17:17:38 +00003516
3517 // T& operator[](T*, ptrdiff_t)
3518 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3519
3520 // T& operator[](ptrdiff_t, T*);
3521 ParamTypes[0] = ParamTypes[1];
3522 ParamTypes[1] = *Ptr;
3523 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3524 }
3525 break;
3526
3527 case OO_ArrowStar:
3528 // FIXME: No support for pointer-to-members yet.
3529 break;
Sebastian Redlbd261962009-04-16 17:51:27 +00003530
3531 case OO_Conditional:
3532 // Note that we don't consider the first argument, since it has been
3533 // contextually converted to bool long ago. The candidates below are
3534 // therefore added as binary.
3535 //
3536 // C++ [over.built]p24:
3537 // For every type T, where T is a pointer or pointer-to-member type,
3538 // there exist candidate operator functions of the form
3539 //
3540 // T operator?(bool, T, T);
3541 //
Sebastian Redlbd261962009-04-16 17:51:27 +00003542 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3543 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3544 QualType ParamTypes[2] = { *Ptr, *Ptr };
3545 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3546 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00003547 for (BuiltinCandidateTypeSet::iterator Ptr =
3548 CandidateTypes.member_pointer_begin(),
3549 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3550 QualType ParamTypes[2] = { *Ptr, *Ptr };
3551 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3552 }
Sebastian Redlbd261962009-04-16 17:51:27 +00003553 goto Conditional;
Douglas Gregor70d26122008-11-12 17:17:38 +00003554 }
3555}
3556
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003557/// \brief Add function candidates found via argument-dependent lookup
3558/// to the set of overloading candidates.
3559///
3560/// This routine performs argument-dependent name lookup based on the
3561/// given function name (which may also be an operator name) and adds
3562/// all of the overload candidates found by ADL to the overload
3563/// candidate set (C++ [basic.lookup.argdep]).
3564void
3565Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3566 Expr **Args, unsigned NumArgs,
3567 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003568 FunctionSet Functions;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003569
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003570 // Record all of the function candidates that we've already
3571 // added to the overload set, so that we don't add those same
3572 // candidates a second time.
3573 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3574 CandEnd = CandidateSet.end();
3575 Cand != CandEnd; ++Cand)
Douglas Gregor993a0602009-06-27 21:05:07 +00003576 if (Cand->Function) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003577 Functions.insert(Cand->Function);
Douglas Gregor993a0602009-06-27 21:05:07 +00003578 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3579 Functions.insert(FunTmpl);
3580 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003581
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003582 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003583
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003584 // Erase all of the candidates we already knew about.
3585 // FIXME: This is suboptimal. Is there a better way?
3586 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3587 CandEnd = CandidateSet.end();
3588 Cand != CandEnd; ++Cand)
Douglas Gregor993a0602009-06-27 21:05:07 +00003589 if (Cand->Function) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003590 Functions.erase(Cand->Function);
Douglas Gregor993a0602009-06-27 21:05:07 +00003591 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3592 Functions.erase(FunTmpl);
3593 }
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003594
3595 // For each of the ADL candidates we found, add it to the overload
3596 // set.
3597 for (FunctionSet::iterator Func = Functions.begin(),
3598 FuncEnd = Functions.end();
Douglas Gregor993a0602009-06-27 21:05:07 +00003599 Func != FuncEnd; ++Func) {
3600 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
3601 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet);
3602 else
Douglas Gregorc9a03b72009-06-30 23:57:56 +00003603 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
3604 /*FIXME: explicit args */false, 0, 0,
3605 Args, NumArgs, CandidateSet);
Douglas Gregor993a0602009-06-27 21:05:07 +00003606 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003607}
3608
Douglas Gregord2baafd2008-10-21 16:13:35 +00003609/// isBetterOverloadCandidate - Determines whether the first overload
3610/// candidate is a better candidate than the second (C++ 13.3.3p1).
3611bool
3612Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3613 const OverloadCandidate& Cand2)
3614{
3615 // Define viable functions to be better candidates than non-viable
3616 // functions.
3617 if (!Cand2.Viable)
3618 return Cand1.Viable;
3619 else if (!Cand1.Viable)
3620 return false;
3621
Douglas Gregor3257fb52008-12-22 05:46:06 +00003622 // C++ [over.match.best]p1:
3623 //
3624 // -- if F is a static member function, ICS1(F) is defined such
3625 // that ICS1(F) is neither better nor worse than ICS1(G) for
3626 // any function G, and, symmetrically, ICS1(G) is neither
3627 // better nor worse than ICS1(F).
3628 unsigned StartArg = 0;
3629 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3630 StartArg = 1;
Douglas Gregord2baafd2008-10-21 16:13:35 +00003631
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003632 // C++ [over.match.best]p1:
3633 // A viable function F1 is defined to be a better function than another
3634 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
3635 // conversion sequence than ICSi(F2), and then...
Douglas Gregord2baafd2008-10-21 16:13:35 +00003636 unsigned NumArgs = Cand1.Conversions.size();
3637 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3638 bool HasBetterConversion = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00003639 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00003640 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3641 Cand2.Conversions[ArgIdx])) {
3642 case ImplicitConversionSequence::Better:
3643 // Cand1 has a better conversion sequence.
3644 HasBetterConversion = true;
3645 break;
3646
3647 case ImplicitConversionSequence::Worse:
3648 // Cand1 can't be better than Cand2.
3649 return false;
3650
3651 case ImplicitConversionSequence::Indistinguishable:
3652 // Do nothing.
3653 break;
3654 }
3655 }
3656
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003657 // -- for some argument j, ICSj(F1) is a better conversion sequence than
3658 // ICSj(F2), or, if not that,
Douglas Gregord2baafd2008-10-21 16:13:35 +00003659 if (HasBetterConversion)
3660 return true;
3661
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003662 // - F1 is a non-template function and F2 is a function template
3663 // specialization, or, if not that,
3664 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3665 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3666 return true;
3667
3668 // -- F1 and F2 are function template specializations, and the function
3669 // template for F1 is more specialized than the template for F2
3670 // according to the partial ordering rules described in 14.5.5.2, or,
3671 // if not that,
Douglas Gregorf8e51672009-08-02 23:46:29 +00003672 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3673 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor8c860df2009-08-21 23:19:43 +00003674 if (FunctionTemplateDecl *BetterTemplate
3675 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3676 Cand2.Function->getPrimaryTemplate(),
3677 true))
3678 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003679
Douglas Gregor60714f92008-11-07 22:36:19 +00003680 // -- the context is an initialization by user-defined conversion
3681 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3682 // from the return type of F1 to the destination type (i.e.,
3683 // the type of the entity being initialized) is a better
3684 // conversion sequence than the standard conversion sequence
3685 // from the return type of F2 to the destination type.
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003686 if (Cand1.Function && Cand2.Function &&
3687 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregor60714f92008-11-07 22:36:19 +00003688 isa<CXXConversionDecl>(Cand2.Function)) {
3689 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3690 Cand2.FinalConversion)) {
3691 case ImplicitConversionSequence::Better:
3692 // Cand1 has a better conversion sequence.
3693 return true;
3694
3695 case ImplicitConversionSequence::Worse:
3696 // Cand1 can't be better than Cand2.
3697 return false;
3698
3699 case ImplicitConversionSequence::Indistinguishable:
3700 // Do nothing
3701 break;
3702 }
3703 }
3704
Douglas Gregord2baafd2008-10-21 16:13:35 +00003705 return false;
3706}
3707
Douglas Gregor98189262009-06-19 23:52:42 +00003708/// \brief Computes the best viable function (C++ 13.3.3)
3709/// within an overload candidate set.
3710///
3711/// \param CandidateSet the set of candidate functions.
3712///
3713/// \param Loc the location of the function name (or operator symbol) for
3714/// which overload resolution occurs.
3715///
3716/// \param Best f overload resolution was successful or found a deleted
3717/// function, Best points to the candidate function found.
3718///
3719/// \returns The result of overload resolution.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003720Sema::OverloadingResult
3721Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregor98189262009-06-19 23:52:42 +00003722 SourceLocation Loc,
Douglas Gregord2baafd2008-10-21 16:13:35 +00003723 OverloadCandidateSet::iterator& Best)
3724{
3725 // Find the best viable function.
3726 Best = CandidateSet.end();
3727 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3728 Cand != CandidateSet.end(); ++Cand) {
3729 if (Cand->Viable) {
3730 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3731 Best = Cand;
3732 }
3733 }
3734
3735 // If we didn't find any viable functions, abort.
3736 if (Best == CandidateSet.end())
3737 return OR_No_Viable_Function;
3738
3739 // Make sure that this function is better than every other viable
3740 // function. If not, we have an ambiguity.
3741 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3742 Cand != CandidateSet.end(); ++Cand) {
3743 if (Cand->Viable &&
3744 Cand != Best &&
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003745 !isBetterOverloadCandidate(*Best, *Cand)) {
3746 Best = CandidateSet.end();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003747 return OR_Ambiguous;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003748 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003749 }
3750
3751 // Best is the best viable function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00003752 if (Best->Function &&
3753 (Best->Function->isDeleted() ||
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003754 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregoraa57e862009-02-18 21:56:37 +00003755 return OR_Deleted;
3756
Douglas Gregor98189262009-06-19 23:52:42 +00003757 // C++ [basic.def.odr]p2:
3758 // An overloaded function is used if it is selected by overload resolution
3759 // when referred to from a potentially-evaluated expression. [Note: this
3760 // covers calls to named functions (5.2.2), operator overloading
3761 // (clause 13), user-defined conversions (12.3.2), allocation function for
3762 // placement new (5.3.4), as well as non-default initialization (8.5).
3763 if (Best->Function)
3764 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregord2baafd2008-10-21 16:13:35 +00003765 return OR_Success;
3766}
3767
3768/// PrintOverloadCandidates - When overload resolution fails, prints
3769/// diagnostic messages containing the candidates in the candidate
3770/// set. If OnlyViable is true, only viable candidates will be printed.
3771void
3772Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3773 bool OnlyViable)
3774{
3775 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3776 LastCand = CandidateSet.end();
3777 for (; Cand != LastCand; ++Cand) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003778 if (Cand->Viable || !OnlyViable) {
3779 if (Cand->Function) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003780 if (Cand->Function->isDeleted() ||
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003781 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003782 // Deleted or "unavailable" function.
3783 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3784 << Cand->Function->isDeleted();
3785 } else {
3786 // Normal function
3787 // FIXME: Give a better reason!
3788 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3789 }
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003790 } else if (Cand->IsSurrogate) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003791 // Desugar the type of the surrogate down to a function type,
3792 // retaining as many typedefs as possible while still showing
3793 // the function type (and, therefore, its parameter types).
3794 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003795 bool isLValueReference = false;
3796 bool isRValueReference = false;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003797 bool isPointer = false;
Sebastian Redlce6fff02009-03-16 23:22:08 +00003798 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003799 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003800 FnType = FnTypeRef->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003801 isLValueReference = true;
3802 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003803 FnType->getAs<RValueReferenceType>()) {
Sebastian Redlce6fff02009-03-16 23:22:08 +00003804 FnType = FnTypeRef->getPointeeType();
3805 isRValueReference = true;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003806 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003807 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003808 FnType = FnTypePtr->getPointeeType();
3809 isPointer = true;
3810 }
3811 // Desugar down to a function type.
3812 FnType = QualType(FnType->getAsFunctionType(), 0);
3813 // Reconstruct the pointer/reference as appropriate.
3814 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redlce6fff02009-03-16 23:22:08 +00003815 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3816 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003817
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003818 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003819 << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003820 } else {
3821 // FIXME: We need to get the identifier in here
Mike Stumpe127ae32009-05-16 07:39:55 +00003822 // FIXME: Do we want the error message to point at the operator?
3823 // (built-ins won't have a location)
Douglas Gregor70d26122008-11-12 17:17:38 +00003824 QualType FnType
3825 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3826 Cand->BuiltinTypes.ParamTypes,
3827 Cand->Conversions.size(),
3828 false, 0);
3829
Chris Lattner4bfd2232008-11-24 06:25:27 +00003830 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003831 }
3832 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003833 }
3834}
3835
Douglas Gregor45014fd2008-11-10 20:40:00 +00003836/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3837/// an overloaded function (C++ [over.over]), where @p From is an
3838/// expression with overloaded function type and @p ToType is the type
3839/// we're trying to resolve to. For example:
3840///
3841/// @code
3842/// int f(double);
3843/// int f(int);
3844///
3845/// int (*pfd)(double) = f; // selects f(double)
3846/// @endcode
3847///
3848/// This routine returns the resulting FunctionDecl if it could be
3849/// resolved, and NULL otherwise. When @p Complain is true, this
3850/// routine will emit diagnostics if there is an error.
3851FunctionDecl *
Sebastian Redl7434fc32009-02-04 21:23:32 +00003852Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor45014fd2008-11-10 20:40:00 +00003853 bool Complain) {
3854 QualType FunctionType = ToType;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003855 bool IsMember = false;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003856 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003857 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003858 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003859 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl7434fc32009-02-04 21:23:32 +00003860 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003861 ToType->getAs<MemberPointerType>()) {
Sebastian Redl7434fc32009-02-04 21:23:32 +00003862 FunctionType = MemTypePtr->getPointeeType();
3863 IsMember = true;
3864 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003865
3866 // We only look at pointers or references to functions.
Douglas Gregor72bb4992009-07-09 17:16:51 +00003867 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor62f78762009-07-08 20:55:45 +00003868 if (!FunctionType->isFunctionType())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003869 return 0;
3870
3871 // Find the actual overloaded function declaration.
3872 OverloadedFunctionDecl *Ovl = 0;
3873
3874 // C++ [over.over]p1:
3875 // [...] [Note: any redundant set of parentheses surrounding the
3876 // overloaded function name is ignored (5.1). ]
3877 Expr *OvlExpr = From->IgnoreParens();
3878
3879 // C++ [over.over]p1:
3880 // [...] The overloaded function name can be preceded by the &
3881 // operator.
3882 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3883 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3884 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3885 }
3886
3887 // Try to dig out the overloaded function.
Douglas Gregor62f78762009-07-08 20:55:45 +00003888 FunctionTemplateDecl *FunctionTemplate = 0;
3889 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003890 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor62f78762009-07-08 20:55:45 +00003891 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
3892 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003893
Douglas Gregor62f78762009-07-08 20:55:45 +00003894 // If there's no overloaded function declaration or function template,
3895 // we're done.
3896 if (!Ovl && !FunctionTemplate)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003897 return 0;
3898
Douglas Gregor62f78762009-07-08 20:55:45 +00003899 OverloadIterator Fun;
3900 if (Ovl)
3901 Fun = Ovl;
3902 else
3903 Fun = FunctionTemplate;
3904
Douglas Gregor45014fd2008-11-10 20:40:00 +00003905 // Look through all of the overloaded functions, searching for one
3906 // whose type matches exactly.
Douglas Gregora142a052009-07-08 23:33:52 +00003907 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
3908
3909 bool FoundNonTemplateFunction = false;
Douglas Gregor62f78762009-07-08 20:55:45 +00003910 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003911 // C++ [over.over]p3:
3912 // Non-member functions and static member functions match
Sebastian Redl3a75abf2009-02-05 12:33:33 +00003913 // targets of type "pointer-to-function" or "reference-to-function."
3914 // Nonstatic member functions match targets of
Sebastian Redl7434fc32009-02-04 21:23:32 +00003915 // type "pointer-to-member-function."
3916 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor62f78762009-07-08 20:55:45 +00003917
3918 if (FunctionTemplateDecl *FunctionTemplate
3919 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Douglas Gregora142a052009-07-08 23:33:52 +00003920 if (CXXMethodDecl *Method
3921 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
3922 // Skip non-static function templates when converting to pointer, and
3923 // static when converting to member pointer.
3924 if (Method->isStatic() == IsMember)
3925 continue;
3926 } else if (IsMember)
3927 continue;
3928
3929 // C++ [over.over]p2:
3930 // If the name is a function template, template argument deduction is
3931 // done (14.8.2.2), and if the argument deduction succeeds, the
3932 // resulting template argument list is used to generate a single
3933 // function template specialization, which is added to the set of
3934 // overloaded functions considered.
Douglas Gregor62f78762009-07-08 20:55:45 +00003935 FunctionDecl *Specialization = 0;
3936 TemplateDeductionInfo Info(Context);
3937 if (TemplateDeductionResult Result
3938 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
3939 /*FIXME:*/0, /*FIXME:*/0,
3940 FunctionType, Specialization, Info)) {
3941 // FIXME: make a note of the failed deduction for diagnostics.
3942 (void)Result;
3943 } else {
3944 assert(FunctionType
3945 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregora142a052009-07-08 23:33:52 +00003946 Matches.insert(
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00003947 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor62f78762009-07-08 20:55:45 +00003948 }
3949 }
3950
Sebastian Redl7434fc32009-02-04 21:23:32 +00003951 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3952 // Skip non-static functions when converting to pointer, and static
3953 // when converting to member pointer.
3954 if (Method->isStatic() == IsMember)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003955 continue;
Douglas Gregora142a052009-07-08 23:33:52 +00003956 } else if (IsMember)
Sebastian Redl7434fc32009-02-04 21:23:32 +00003957 continue;
Douglas Gregor45014fd2008-11-10 20:40:00 +00003958
Douglas Gregorb60eb752009-06-25 22:08:12 +00003959 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregora142a052009-07-08 23:33:52 +00003960 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00003961 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregora142a052009-07-08 23:33:52 +00003962 FoundNonTemplateFunction = true;
3963 }
Douglas Gregor62f78762009-07-08 20:55:45 +00003964 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003965 }
3966
Douglas Gregora142a052009-07-08 23:33:52 +00003967 // If there were 0 or 1 matches, we're done.
3968 if (Matches.empty())
3969 return 0;
3970 else if (Matches.size() == 1)
3971 return *Matches.begin();
3972
3973 // C++ [over.over]p4:
3974 // If more than one function is selected, [...]
3975 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
Douglas Gregor8c860df2009-08-21 23:19:43 +00003976 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregora142a052009-07-08 23:33:52 +00003977 if (FoundNonTemplateFunction) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00003978 // [...] any function template specializations in the set are
3979 // eliminated if the set also contains a non-template function, [...]
3980 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
Douglas Gregora142a052009-07-08 23:33:52 +00003981 if ((*M)->getPrimaryTemplate() == 0)
3982 RemainingMatches.push_back(*M);
3983 } else {
Douglas Gregor8c860df2009-08-21 23:19:43 +00003984 // [...] and any given function template specialization F1 is
3985 // eliminated if the set contains a second function template
3986 // specialization whose function template is more specialized
3987 // than the function template of F1 according to the partial
3988 // ordering rules of 14.5.5.2.
3989
3990 // The algorithm specified above is quadratic. We instead use a
3991 // two-pass algorithm (similar to the one used to identify the
3992 // best viable function in an overload set) that identifies the
3993 // best function template (if it exists).
3994 MatchIter Best = Matches.begin();
3995 MatchIter M = Best, MEnd = Matches.end();
3996 // Find the most specialized function.
3997 for (++M; M != MEnd; ++M)
3998 if (getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
3999 (*Best)->getPrimaryTemplate(),
4000 false)
4001 == (*M)->getPrimaryTemplate())
4002 Best = M;
4003
4004 // Determine whether this function template is more specialized
4005 // that all of the others.
4006 bool Ambiguous = false;
4007 for (M = Matches.begin(); M != MEnd; ++M) {
4008 if (M != Best &&
4009 getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4010 (*Best)->getPrimaryTemplate(),
4011 false)
4012 != (*Best)->getPrimaryTemplate()) {
4013 Ambiguous = true;
4014 break;
4015 }
4016 }
4017
4018 // If one function template was more specialized than all of the
4019 // others, return it.
4020 if (!Ambiguous)
4021 return *Best;
4022
4023 // We could not find a most-specialized function template, which
4024 // is equivalent to having a set of function templates with more
4025 // than one such template. So, we place all of the function
4026 // templates into the set of remaining matches and produce a
4027 // diagnostic below. FIXME: we could perform the quadratic
4028 // algorithm here, pruning the result set to limit the number of
4029 // candidates output later.
4030 RemainingMatches.append(Matches.begin(), Matches.end());
Douglas Gregora142a052009-07-08 23:33:52 +00004031 }
4032
4033 // [...] After such eliminations, if any, there shall remain exactly one
4034 // selected function.
4035 if (RemainingMatches.size() == 1)
4036 return RemainingMatches.front();
4037
4038 // FIXME: We should probably return the same thing that BestViableFunction
4039 // returns (even if we issue the diagnostics here).
4040 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4041 << RemainingMatches[0]->getDeclName();
4042 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4043 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregor45014fd2008-11-10 20:40:00 +00004044 return 0;
4045}
4046
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004047/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004048/// (which eventually refers to the declaration Func) and the call
4049/// arguments Args/NumArgs, attempt to resolve the function call down
4050/// to a specific function. If overload resolution succeeds, returns
4051/// the function declaration produced by overload
Douglas Gregorbf4f0582008-11-26 06:01:48 +00004052/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004053/// arguments and Fn, and returns NULL.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004054FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004055 DeclarationName UnqualifiedName,
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004056 bool HasExplicitTemplateArgs,
4057 const TemplateArgument *ExplicitTemplateArgs,
4058 unsigned NumExplicitTemplateArgs,
Douglas Gregorbf4f0582008-11-26 06:01:48 +00004059 SourceLocation LParenLoc,
4060 Expr **Args, unsigned NumArgs,
4061 SourceLocation *CommaLocs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004062 SourceLocation RParenLoc,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004063 bool &ArgumentDependentLookup) {
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004064 OverloadCandidateSet CandidateSet;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004065
4066 // Add the functions denoted by Callee to the set of candidate
4067 // functions. While we're doing so, track whether argument-dependent
4068 // lookup still applies, per:
4069 //
4070 // C++0x [basic.lookup.argdep]p3:
4071 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4072 // and let Y be the lookup set produced by argument dependent
4073 // lookup (defined as follows). If X contains
4074 //
4075 // -- a declaration of a class member, or
4076 //
4077 // -- a block-scope function declaration that is not a
4078 // using-declaration, or
4079 //
4080 // -- a declaration that is neither a function or a function
4081 // template
4082 //
4083 // then Y is empty.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004084 if (OverloadedFunctionDecl *Ovl
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004085 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
4086 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4087 FuncEnd = Ovl->function_end();
4088 Func != FuncEnd; ++Func) {
Douglas Gregorb60eb752009-06-25 22:08:12 +00004089 DeclContext *Ctx = 0;
4090 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Func)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004091 if (HasExplicitTemplateArgs)
4092 continue;
4093
Douglas Gregorb60eb752009-06-25 22:08:12 +00004094 AddOverloadCandidate(FunDecl, Args, NumArgs, CandidateSet);
4095 Ctx = FunDecl->getDeclContext();
4096 } else {
4097 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*Func);
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004098 AddTemplateOverloadCandidate(FunTmpl, HasExplicitTemplateArgs,
4099 ExplicitTemplateArgs,
4100 NumExplicitTemplateArgs,
4101 Args, NumArgs, CandidateSet);
Douglas Gregorb60eb752009-06-25 22:08:12 +00004102 Ctx = FunTmpl->getDeclContext();
4103 }
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004104
Douglas Gregorb60eb752009-06-25 22:08:12 +00004105
4106 if (Ctx->isRecord() || Ctx->isFunctionOrMethod())
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004107 ArgumentDependentLookup = false;
4108 }
4109 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004110 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004111 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
4112
4113 if (Func->getDeclContext()->isRecord() ||
4114 Func->getDeclContext()->isFunctionOrMethod())
4115 ArgumentDependentLookup = false;
Douglas Gregorb60eb752009-06-25 22:08:12 +00004116 } else if (FunctionTemplateDecl *FuncTemplate
4117 = dyn_cast_or_null<FunctionTemplateDecl>(Callee)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004118 AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4119 ExplicitTemplateArgs,
4120 NumExplicitTemplateArgs,
4121 Args, NumArgs, CandidateSet);
Douglas Gregorb60eb752009-06-25 22:08:12 +00004122
4123 if (FuncTemplate->getDeclContext()->isRecord())
4124 ArgumentDependentLookup = false;
4125 }
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004126
4127 if (Callee)
4128 UnqualifiedName = Callee->getDeclName();
4129
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004130 // FIXME: Pass explicit template arguments through for ADL
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004131 if (ArgumentDependentLookup)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004132 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004133 CandidateSet);
4134
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004135 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004136 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00004137 case OR_Success:
4138 return Best->Function;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004139
4140 case OR_No_Viable_Function:
Chris Lattner4a526112009-02-17 07:29:20 +00004141 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004142 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004143 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004144 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4145 break;
4146
4147 case OR_Ambiguous:
4148 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004149 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004150 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4151 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004152
4153 case OR_Deleted:
4154 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4155 << Best->Function->isDeleted()
4156 << UnqualifiedName
4157 << Fn->getSourceRange();
4158 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4159 break;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004160 }
4161
4162 // Overload resolution failed. Destroy all of the subexpressions and
4163 // return NULL.
4164 Fn->Destroy(Context);
4165 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4166 Args[Arg]->Destroy(Context);
4167 return 0;
4168}
4169
Douglas Gregorc78182d2009-03-13 23:49:33 +00004170/// \brief Create a unary operation that may resolve to an overloaded
4171/// operator.
4172///
4173/// \param OpLoc The location of the operator itself (e.g., '*').
4174///
4175/// \param OpcIn The UnaryOperator::Opcode that describes this
4176/// operator.
4177///
4178/// \param Functions The set of non-member functions that will be
4179/// considered by overload resolution. The caller needs to build this
4180/// set based on the context using, e.g.,
4181/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4182/// set should not contain any member functions; those will be added
4183/// by CreateOverloadedUnaryOp().
4184///
4185/// \param input The input argument.
4186Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4187 unsigned OpcIn,
4188 FunctionSet &Functions,
4189 ExprArg input) {
4190 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4191 Expr *Input = (Expr *)input.get();
4192
4193 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4194 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4195 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4196
4197 Expr *Args[2] = { Input, 0 };
4198 unsigned NumArgs = 1;
4199
4200 // For post-increment and post-decrement, add the implicit '0' as
4201 // the second argument, so that we know this is a post-increment or
4202 // post-decrement.
4203 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4204 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
4205 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
4206 SourceLocation());
4207 NumArgs = 2;
4208 }
4209
4210 if (Input->isTypeDependent()) {
4211 OverloadedFunctionDecl *Overloads
4212 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4213 for (FunctionSet::iterator Func = Functions.begin(),
4214 FuncEnd = Functions.end();
4215 Func != FuncEnd; ++Func)
4216 Overloads->addOverload(*Func);
4217
4218 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4219 OpLoc, false, false);
4220
4221 input.release();
4222 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4223 &Args[0], NumArgs,
4224 Context.DependentTy,
4225 OpLoc));
4226 }
4227
4228 // Build an empty overload set.
4229 OverloadCandidateSet CandidateSet;
4230
4231 // Add the candidates from the given function set.
4232 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4233
4234 // Add operator candidates that are member functions.
4235 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4236
4237 // Add builtin operator candidates.
4238 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4239
4240 // Perform overload resolution.
4241 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004242 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00004243 case OR_Success: {
4244 // We found a built-in operator or an overloaded operator.
4245 FunctionDecl *FnDecl = Best->Function;
4246
4247 if (FnDecl) {
4248 // We matched an overloaded operator. Build a call to that
4249 // operator.
4250
4251 // Convert the arguments.
4252 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4253 if (PerformObjectArgumentInitialization(Input, Method))
4254 return ExprError();
4255 } else {
4256 // Convert the arguments.
4257 if (PerformCopyInitialization(Input,
4258 FnDecl->getParamDecl(0)->getType(),
4259 "passing"))
4260 return ExprError();
4261 }
4262
4263 // Determine the result type
4264 QualType ResultTy
4265 = FnDecl->getType()->getAsFunctionType()->getResultType();
4266 ResultTy = ResultTy.getNonReferenceType();
4267
4268 // Build the actual expression node.
4269 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4270 SourceLocation());
4271 UsualUnaryConversions(FnExpr);
4272
4273 input.release();
Anders Carlsson16497742009-08-16 04:11:06 +00004274
4275 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4276 &Input, 1, ResultTy, OpLoc);
4277 return MaybeBindToTemporary(CE);
Douglas Gregorc78182d2009-03-13 23:49:33 +00004278 } else {
4279 // We matched a built-in operator. Convert the arguments, then
4280 // break out so that we will build the appropriate built-in
4281 // operator node.
4282 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4283 Best->Conversions[0], "passing"))
4284 return ExprError();
4285
4286 break;
4287 }
4288 }
4289
4290 case OR_No_Viable_Function:
4291 // No viable function; fall through to handling this as a
4292 // built-in operator, which will produce an error message for us.
4293 break;
4294
4295 case OR_Ambiguous:
4296 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4297 << UnaryOperator::getOpcodeStr(Opc)
4298 << Input->getSourceRange();
4299 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4300 return ExprError();
4301
4302 case OR_Deleted:
4303 Diag(OpLoc, diag::err_ovl_deleted_oper)
4304 << Best->Function->isDeleted()
4305 << UnaryOperator::getOpcodeStr(Opc)
4306 << Input->getSourceRange();
4307 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4308 return ExprError();
4309 }
4310
4311 // Either we found no viable overloaded operator or we matched a
4312 // built-in operator. In either case, fall through to trying to
4313 // build a built-in operation.
4314 input.release();
4315 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4316}
4317
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004318/// \brief Create a binary operation that may resolve to an overloaded
4319/// operator.
4320///
4321/// \param OpLoc The location of the operator itself (e.g., '+').
4322///
4323/// \param OpcIn The BinaryOperator::Opcode that describes this
4324/// operator.
4325///
4326/// \param Functions The set of non-member functions that will be
4327/// considered by overload resolution. The caller needs to build this
4328/// set based on the context using, e.g.,
4329/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4330/// set should not contain any member functions; those will be added
4331/// by CreateOverloadedBinOp().
4332///
4333/// \param LHS Left-hand argument.
4334/// \param RHS Right-hand argument.
4335Sema::OwningExprResult
4336Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
4337 unsigned OpcIn,
4338 FunctionSet &Functions,
4339 Expr *LHS, Expr *RHS) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004340 Expr *Args[2] = { LHS, RHS };
Douglas Gregor114c6192009-08-26 17:08:25 +00004341 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004342
4343 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4344 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4345 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4346
4347 // If either side is type-dependent, create an appropriate dependent
4348 // expression.
Douglas Gregor114c6192009-08-26 17:08:25 +00004349 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004350 // .* cannot be overloaded.
4351 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregor114c6192009-08-26 17:08:25 +00004352 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004353 Context.DependentTy, OpLoc));
4354
4355 OverloadedFunctionDecl *Overloads
4356 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4357 for (FunctionSet::iterator Func = Functions.begin(),
4358 FuncEnd = Functions.end();
4359 Func != FuncEnd; ++Func)
4360 Overloads->addOverload(*Func);
4361
4362 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4363 OpLoc, false, false);
4364
4365 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4366 Args, 2,
4367 Context.DependentTy,
4368 OpLoc));
4369 }
4370
4371 // If this is the .* operator, which is not overloadable, just
4372 // create a built-in binary operator.
4373 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregor114c6192009-08-26 17:08:25 +00004374 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004375
4376 // If this is one of the assignment operators, we only perform
4377 // overload resolution if the left-hand side is a class or
4378 // enumeration type (C++ [expr.ass]p3).
4379 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregor114c6192009-08-26 17:08:25 +00004380 !Args[0]->getType()->isOverloadableType())
4381 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004382
Douglas Gregorc78182d2009-03-13 23:49:33 +00004383 // Build an empty overload set.
4384 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004385
4386 // Add the candidates from the given function set.
4387 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4388
4389 // Add operator candidates that are member functions.
4390 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4391
4392 // Add builtin operator candidates.
4393 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4394
4395 // Perform overload resolution.
4396 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004397 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00004398 case OR_Success: {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004399 // We found a built-in operator or an overloaded operator.
4400 FunctionDecl *FnDecl = Best->Function;
4401
4402 if (FnDecl) {
4403 // We matched an overloaded operator. Build a call to that
4404 // operator.
4405
4406 // Convert the arguments.
4407 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregor114c6192009-08-26 17:08:25 +00004408 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4409 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004410 "passing"))
4411 return ExprError();
4412 } else {
4413 // Convert the arguments.
Douglas Gregor114c6192009-08-26 17:08:25 +00004414 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004415 "passing") ||
Douglas Gregor114c6192009-08-26 17:08:25 +00004416 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004417 "passing"))
4418 return ExprError();
4419 }
4420
4421 // Determine the result type
4422 QualType ResultTy
4423 = FnDecl->getType()->getAsFunctionType()->getResultType();
4424 ResultTy = ResultTy.getNonReferenceType();
4425
4426 // Build the actual expression node.
4427 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argiris Kirtzidiscca21b82009-07-14 03:19:38 +00004428 OpLoc);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004429 UsualUnaryConversions(FnExpr);
4430
Anders Carlsson16497742009-08-16 04:11:06 +00004431 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4432 Args, 2, ResultTy, OpLoc);
4433 return MaybeBindToTemporary(CE);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004434 } else {
4435 // We matched a built-in operator. Convert the arguments, then
4436 // break out so that we will build the appropriate built-in
4437 // operator node.
Douglas Gregor114c6192009-08-26 17:08:25 +00004438 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004439 Best->Conversions[0], "passing") ||
Douglas Gregor114c6192009-08-26 17:08:25 +00004440 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004441 Best->Conversions[1], "passing"))
4442 return ExprError();
4443
4444 break;
4445 }
4446 }
4447
4448 case OR_No_Viable_Function:
Sebastian Redl35196b42009-05-21 11:50:50 +00004449 // For class as left operand for assignment or compound assigment operator
4450 // do not fall through to handling in built-in, but report that no overloaded
4451 // assignment operator found
Douglas Gregor114c6192009-08-26 17:08:25 +00004452 if (Args[0]->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl35196b42009-05-21 11:50:50 +00004453 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4454 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor114c6192009-08-26 17:08:25 +00004455 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Sebastian Redl35196b42009-05-21 11:50:50 +00004456 return ExprError();
4457 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004458 // No viable function; fall through to handling this as a
4459 // built-in operator, which will produce an error message for us.
4460 break;
4461
4462 case OR_Ambiguous:
4463 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4464 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor114c6192009-08-26 17:08:25 +00004465 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004466 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4467 return ExprError();
4468
4469 case OR_Deleted:
4470 Diag(OpLoc, diag::err_ovl_deleted_oper)
4471 << Best->Function->isDeleted()
4472 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor114c6192009-08-26 17:08:25 +00004473 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004474 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4475 return ExprError();
4476 }
4477
4478 // Either we found no viable overloaded operator or we matched a
4479 // built-in operator. In either case, try to build a built-in
4480 // operation.
Douglas Gregor114c6192009-08-26 17:08:25 +00004481 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004482}
4483
Douglas Gregor3257fb52008-12-22 05:46:06 +00004484/// BuildCallToMemberFunction - Build a call to a member
4485/// function. MemExpr is the expression that refers to the member
4486/// function (and includes the object parameter), Args/NumArgs are the
4487/// arguments to the function call (not including the object
4488/// parameter). The caller needs to validate that the member
4489/// expression refers to a member function or an overloaded member
4490/// function.
4491Sema::ExprResult
4492Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4493 SourceLocation LParenLoc, Expr **Args,
4494 unsigned NumArgs, SourceLocation *CommaLocs,
4495 SourceLocation RParenLoc) {
4496 // Dig out the member expression. This holds both the object
4497 // argument and the member function we're referring to.
4498 MemberExpr *MemExpr = 0;
4499 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4500 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4501 else
4502 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4503 assert(MemExpr && "Building member call without member expression");
4504
4505 // Extract the object argument.
4506 Expr *ObjectArg = MemExpr->getBase();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00004507
Douglas Gregor3257fb52008-12-22 05:46:06 +00004508 CXXMethodDecl *Method = 0;
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004509 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4510 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00004511 // Add overload candidates
4512 OverloadCandidateSet CandidateSet;
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004513 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
4514
Douglas Gregor050cabf2009-08-21 18:42:58 +00004515 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4516 Func != FuncEnd; ++Func) {
4517 if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
4518 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
4519 /*SuppressUserConversions=*/false);
4520 else
4521 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4522 /*FIXME:*/false, /*FIXME:*/0,
4523 /*FIXME:*/0, ObjectArg, Args, NumArgs,
4524 CandidateSet,
4525 /*SuppressUsedConversions=*/false);
4526 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004527
Douglas Gregor3257fb52008-12-22 05:46:06 +00004528 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004529 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00004530 case OR_Success:
4531 Method = cast<CXXMethodDecl>(Best->Function);
4532 break;
4533
4534 case OR_No_Viable_Function:
4535 Diag(MemExpr->getSourceRange().getBegin(),
4536 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004537 << DeclName << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004538 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4539 // FIXME: Leaking incoming expressions!
4540 return true;
4541
4542 case OR_Ambiguous:
4543 Diag(MemExpr->getSourceRange().getBegin(),
4544 diag::err_ovl_ambiguous_member_call)
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004545 << DeclName << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004546 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4547 // FIXME: Leaking incoming expressions!
4548 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004549
4550 case OR_Deleted:
4551 Diag(MemExpr->getSourceRange().getBegin(),
4552 diag::err_ovl_deleted_member_call)
4553 << Best->Function->isDeleted()
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004554 << DeclName << MemExprE->getSourceRange();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004555 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4556 // FIXME: Leaking incoming expressions!
4557 return true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00004558 }
4559
4560 FixOverloadedFunctionReference(MemExpr, Method);
4561 } else {
4562 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4563 }
4564
4565 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek0c97e042009-02-07 01:47:29 +00004566 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek362abcd2009-02-09 20:51:47 +00004567 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
4568 NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00004569 Method->getResultType().getNonReferenceType(),
4570 RParenLoc));
4571
4572 // Convert the object argument (for a non-static member function call).
4573 if (!Method->isStatic() &&
4574 PerformObjectArgumentInitialization(ObjectArg, Method))
4575 return true;
4576 MemExpr->setBase(ObjectArg);
4577
4578 // Convert the rest of the arguments
Douglas Gregor4fa58902009-02-26 23:50:07 +00004579 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004580 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4581 RParenLoc))
4582 return true;
4583
Anders Carlsson7fb13802009-08-16 01:56:34 +00004584 if (CheckFunctionCall(Method, TheCall.get()))
4585 return true;
Anders Carlssonb8ff3402009-08-16 03:42:12 +00004586
4587 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004588}
4589
Douglas Gregor10f3c502008-11-19 21:05:33 +00004590/// BuildCallToObjectOfClassType - Build a call to an object of class
4591/// type (C++ [over.call.object]), which can end up invoking an
4592/// overloaded function call operator (@c operator()) or performing a
4593/// user-defined conversion on the object argument.
Douglas Gregor3257fb52008-12-22 05:46:06 +00004594Sema::ExprResult
Douglas Gregora133e262008-12-06 00:22:45 +00004595Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4596 SourceLocation LParenLoc,
Douglas Gregor10f3c502008-11-19 21:05:33 +00004597 Expr **Args, unsigned NumArgs,
4598 SourceLocation *CommaLocs,
4599 SourceLocation RParenLoc) {
4600 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004601 const RecordType *Record = Object->getType()->getAs<RecordType>();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004602
4603 // C++ [over.call.object]p1:
4604 // If the primary-expression E in the function call syntax
Eli Friedmand5a72f02009-08-05 19:21:58 +00004605 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor10f3c502008-11-19 21:05:33 +00004606 // candidate functions includes at least the function call
4607 // operators of T. The function call operators of T are obtained by
4608 // ordinary lookup of the name operator() in the context of
4609 // (E).operator().
4610 OverloadCandidateSet CandidateSet;
Douglas Gregor8acb7272008-12-11 16:49:14 +00004611 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004612 DeclContext::lookup_const_iterator Oper, OperEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00004613 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004614 Oper != OperEnd; ++Oper)
4615 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4616 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004617
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004618 // C++ [over.call.object]p2:
4619 // In addition, for each conversion function declared in T of the
4620 // form
4621 //
4622 // operator conversion-type-id () cv-qualifier;
4623 //
4624 // where cv-qualifier is the same cv-qualification as, or a
4625 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregor261afa72008-11-20 13:33:37 +00004626 // denotes the type "pointer to function of (P1,...,Pn) returning
4627 // R", or the type "reference to pointer to function of
4628 // (P1,...,Pn) returning R", or the type "reference to function
4629 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004630 // is also considered as a candidate function. Similarly,
4631 // surrogate call functions are added to the set of candidate
4632 // functions for each conversion function declared in an
4633 // accessible base class provided the function is not hidden
4634 // within T by another intervening declaration.
Douglas Gregorb35c7992009-08-24 15:23:48 +00004635
4636 if (!RequireCompleteType(SourceLocation(), Object->getType(), 0)) {
4637 // FIXME: Look in base classes for more conversion operators!
4638 OverloadedFunctionDecl *Conversions
4639 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
4640 for (OverloadedFunctionDecl::function_iterator
4641 Func = Conversions->function_begin(),
4642 FuncEnd = Conversions->function_end();
4643 Func != FuncEnd; ++Func) {
4644 CXXConversionDecl *Conv;
4645 FunctionTemplateDecl *ConvTemplate;
4646 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Douglas Gregor8c860df2009-08-21 23:19:43 +00004647
Douglas Gregorb35c7992009-08-24 15:23:48 +00004648 // Skip over templated conversion functions; they aren't
4649 // surrogates.
4650 if (ConvTemplate)
4651 continue;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004652
Douglas Gregorb35c7992009-08-24 15:23:48 +00004653 // Strip the reference type (if any) and then the pointer type (if
4654 // any) to get down to what might be a function type.
4655 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4656 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4657 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004658
Douglas Gregorb35c7992009-08-24 15:23:48 +00004659 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
4660 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4661 }
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004662 }
Douglas Gregorb35c7992009-08-24 15:23:48 +00004663
Douglas Gregor10f3c502008-11-19 21:05:33 +00004664 // Perform overload resolution.
4665 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004666 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004667 case OR_Success:
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004668 // Overload resolution succeeded; we'll build the appropriate call
4669 // below.
Douglas Gregor10f3c502008-11-19 21:05:33 +00004670 break;
4671
4672 case OR_No_Viable_Function:
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004673 Diag(Object->getSourceRange().getBegin(),
4674 diag::err_ovl_no_viable_object_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004675 << Object->getType() << Object->getSourceRange();
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004676 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004677 break;
4678
4679 case OR_Ambiguous:
4680 Diag(Object->getSourceRange().getBegin(),
4681 diag::err_ovl_ambiguous_object_call)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004682 << Object->getType() << Object->getSourceRange();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004683 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4684 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004685
4686 case OR_Deleted:
4687 Diag(Object->getSourceRange().getBegin(),
4688 diag::err_ovl_deleted_object_call)
4689 << Best->Function->isDeleted()
4690 << Object->getType() << Object->getSourceRange();
4691 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4692 break;
Douglas Gregor10f3c502008-11-19 21:05:33 +00004693 }
4694
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004695 if (Best == CandidateSet.end()) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004696 // We had an error; delete all of the subexpressions and return
4697 // the error.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004698 Object->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004699 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004700 Args[ArgIdx]->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004701 return true;
4702 }
4703
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004704 if (Best->Function == 0) {
4705 // Since there is no function declaration, this is one of the
4706 // surrogate candidates. Dig out the conversion function.
4707 CXXConversionDecl *Conv
4708 = cast<CXXConversionDecl>(
4709 Best->Conversions[0].UserDefined.ConversionFunction);
4710
4711 // We selected one of the surrogate functions that converts the
4712 // object parameter to a function pointer. Perform the conversion
4713 // on the object argument, then let ActOnCallExpr finish the job.
4714 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl8b769972009-01-19 00:08:26 +00004715 ImpCastExprToType(Object,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004716 Conv->getConversionType().getNonReferenceType(),
Anders Carlsson85186942009-07-31 01:23:52 +00004717 CastExpr::CK_Unknown,
Sebastian Redlce6fff02009-03-16 23:22:08 +00004718 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00004719 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4720 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4721 CommaLocs, RParenLoc).release();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004722 }
4723
4724 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4725 // that calls this method, using Object for the implicit object
4726 // parameter and passing along the remaining arguments.
4727 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004728 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004729
4730 unsigned NumArgsInProto = Proto->getNumArgs();
4731 unsigned NumArgsToCheck = NumArgs;
4732
4733 // Build the full argument list for the method call (the
4734 // implicit object parameter is placed at the beginning of the
4735 // list).
4736 Expr **MethodArgs;
4737 if (NumArgs < NumArgsInProto) {
4738 NumArgsToCheck = NumArgsInProto;
4739 MethodArgs = new Expr*[NumArgsInProto + 1];
4740 } else {
4741 MethodArgs = new Expr*[NumArgs + 1];
4742 }
4743 MethodArgs[0] = Object;
4744 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4745 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4746
Ted Kremenek0c97e042009-02-07 01:47:29 +00004747 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4748 SourceLocation());
Douglas Gregor10f3c502008-11-19 21:05:33 +00004749 UsualUnaryConversions(NewFn);
4750
4751 // Once we've built TheCall, all of the expressions are properly
4752 // owned.
4753 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00004754 ExprOwningPtr<CXXOperatorCallExpr>
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004755 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4756 MethodArgs, NumArgs + 1,
Ted Kremenek0c97e042009-02-07 01:47:29 +00004757 ResultTy, RParenLoc));
Douglas Gregor10f3c502008-11-19 21:05:33 +00004758 delete [] MethodArgs;
4759
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004760 // We may have default arguments. If so, we need to allocate more
4761 // slots in the call for them.
4762 if (NumArgs < NumArgsInProto)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004763 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004764 else if (NumArgs > NumArgsInProto)
4765 NumArgsToCheck = NumArgsInProto;
4766
Chris Lattner81f00ed2009-04-12 08:11:20 +00004767 bool IsError = false;
4768
Douglas Gregor10f3c502008-11-19 21:05:33 +00004769 // Initialize the implicit object parameter.
Chris Lattner81f00ed2009-04-12 08:11:20 +00004770 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004771 TheCall->setArg(0, Object);
4772
Chris Lattner81f00ed2009-04-12 08:11:20 +00004773
Douglas Gregor10f3c502008-11-19 21:05:33 +00004774 // Check the argument types.
4775 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004776 Expr *Arg;
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004777 if (i < NumArgs) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004778 Arg = Args[i];
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004779
4780 // Pass the argument.
4781 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner81f00ed2009-04-12 08:11:20 +00004782 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004783 } else {
Anders Carlsson3d752db2009-08-14 18:30:22 +00004784 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004785 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004786
4787 TheCall->setArg(i + 1, Arg);
4788 }
4789
4790 // If this is a variadic call, handle args passed through "...".
4791 if (Proto->isVariadic()) {
4792 // Promote the arguments (C99 6.5.2.2p7).
4793 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4794 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00004795 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004796 TheCall->setArg(i + 1, Arg);
4797 }
4798 }
4799
Chris Lattner81f00ed2009-04-12 08:11:20 +00004800 if (IsError) return true;
4801
Anders Carlsson7fb13802009-08-16 01:56:34 +00004802 if (CheckFunctionCall(Method, TheCall.get()))
4803 return true;
4804
Anders Carlsson422a5fe2009-08-16 03:53:54 +00004805 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004806}
4807
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004808/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4809/// (if one exists), where @c Base is an expression of class type and
4810/// @c Member is the name of the member we're trying to find.
Douglas Gregorda61ad22009-08-06 03:17:00 +00004811Sema::OwningExprResult
4812Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
4813 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004814 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4815
4816 // C++ [over.ref]p1:
4817 //
4818 // [...] An expression x->m is interpreted as (x.operator->())->m
4819 // for a class object x of type T if T::operator->() exists and if
4820 // the operator is selected as the best match function by the
4821 // overload resolution mechanism (13.3).
4822 // FIXME: look in base classes.
4823 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4824 OverloadCandidateSet CandidateSet;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004825 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorda61ad22009-08-06 03:17:00 +00004826
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004827 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004828 for (llvm::tie(Oper, OperEnd)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00004829 = BaseRecord->getDecl()->lookup(OpName); Oper != OperEnd; ++Oper)
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004830 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004831 /*SuppressUserConversions=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004832
4833 // Perform overload resolution.
4834 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004835 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004836 case OR_Success:
4837 // Overload resolution succeeded; we'll build the call below.
4838 break;
4839
4840 case OR_No_Viable_Function:
4841 if (CandidateSet.empty())
4842 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004843 << Base->getType() << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004844 else
4845 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004846 << "operator->" << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004847 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004848 return ExprError();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004849
4850 case OR_Ambiguous:
4851 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004852 << "operator->" << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004853 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004854 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004855
4856 case OR_Deleted:
4857 Diag(OpLoc, diag::err_ovl_deleted_oper)
4858 << Best->Function->isDeleted()
Douglas Gregorda61ad22009-08-06 03:17:00 +00004859 << "operator->" << Base->getSourceRange();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004860 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004861 return ExprError();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004862 }
4863
4864 // Convert the object parameter.
4865 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004866 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorda61ad22009-08-06 03:17:00 +00004867 return ExprError();
Douglas Gregor9c690e92008-11-21 03:04:22 +00004868
4869 // No concerns about early exits now.
Douglas Gregorda61ad22009-08-06 03:17:00 +00004870 BaseIn.release();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004871
4872 // Build the operator call.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004873 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4874 SourceLocation());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004875 UsualUnaryConversions(FnExpr);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004876 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004877 Method->getResultType().getNonReferenceType(),
4878 OpLoc);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004879 return Owned(Base);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004880}
4881
Douglas Gregor45014fd2008-11-10 20:40:00 +00004882/// FixOverloadedFunctionReference - E is an expression that refers to
4883/// a C++ overloaded function (possibly with some parentheses and
4884/// perhaps a '&' around it). We have resolved the overloaded function
4885/// to the function declaration Fn, so patch up the expression E to
4886/// refer (possibly indirectly) to Fn.
4887void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4888 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4889 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4890 E->setType(PE->getSubExpr()->getType());
4891 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4892 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4893 "Can only take the address of an overloaded function");
Douglas Gregor3f411962009-02-11 01:18:59 +00004894 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4895 if (Method->isStatic()) {
4896 // Do nothing: static member functions aren't any different
4897 // from non-member functions.
Mike Stump90fc78e2009-08-04 21:02:39 +00004898 } else if (QualifiedDeclRefExpr *DRE
Douglas Gregor3f411962009-02-11 01:18:59 +00004899 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4900 // We have taken the address of a pointer to member
4901 // function. Perform the computation here so that we get the
4902 // appropriate pointer to member type.
4903 DRE->setDecl(Fn);
4904 DRE->setType(Fn->getType());
4905 QualType ClassType
4906 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4907 E->setType(Context.getMemberPointerType(Fn->getType(),
4908 ClassType.getTypePtr()));
4909 return;
4910 }
4911 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00004912 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor2eedd992009-02-11 00:19:33 +00004913 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor45014fd2008-11-10 20:40:00 +00004914 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor62f78762009-07-08 20:55:45 +00004915 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
4916 isa<FunctionTemplateDecl>(DR->getDecl())) &&
4917 "Expected overloaded function or function template");
Douglas Gregor45014fd2008-11-10 20:40:00 +00004918 DR->setDecl(Fn);
4919 E->setType(Fn->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004920 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4921 MemExpr->setMemberDecl(Fn);
4922 E->setType(Fn->getType());
Douglas Gregor45014fd2008-11-10 20:40:00 +00004923 } else {
4924 assert(false && "Invalid reference to overloaded function");
4925 }
4926}
4927
Douglas Gregord2baafd2008-10-21 16:13:35 +00004928} // end namespace clang