blob: f22c1177e645bc1b4bb7a94ff74849588ddedae0 [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 Carlssonfcc53032009-08-27 17:14:02 +0000411Sema::TryImplicitConversion(Expr* From, QualType ToType,
412 bool SuppressUserConversions,
Anders Carlsson8e4c1692009-08-28 15:33:32 +0000413 bool AllowExplicit, bool ForceRValue,
414 bool InOverloadResolution)
Anders Carlssonfcc53032009-08-27 17:14:02 +0000415{
Douglas Gregord2baafd2008-10-21 16:13:35 +0000416 ImplicitConversionSequence ICS;
Anders Carlsson8e4c1692009-08-28 15:33:32 +0000417 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000418 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,
Anders Carlsson8e4c1692009-08-28 15:33:32 +0000475 bool InOverloadResolution,
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000476 StandardConversionSequence &SCS)
477{
Douglas Gregord2baafd2008-10-21 16:13:35 +0000478 QualType FromType = From->getType();
479
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000480 // Standard conversions (C++ [conv])
Douglas Gregor70d26122008-11-12 17:17:38 +0000481 SCS.setAsIdentityConversion();
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000482 SCS.Deprecated = false;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000483 SCS.IncompatibleObjC = false;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000484 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000485 SCS.CopyConstructor = 0;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000486
Douglas Gregorfcb19192009-02-11 23:02:49 +0000487 // There are no standard conversions for class types in C++, so
488 // abort early. When overloading in C, however, we do permit
489 if (FromType->isRecordType() || ToType->isRecordType()) {
490 if (getLangOptions().CPlusPlus)
491 return false;
492
493 // When we're overloading in C, we allow, as standard conversions,
494 }
495
Douglas Gregord2baafd2008-10-21 16:13:35 +0000496 // The first conversion can be an lvalue-to-rvalue conversion,
497 // array-to-pointer conversion, or function-to-pointer conversion
498 // (C++ 4p1).
499
500 // Lvalue-to-rvalue conversion (C++ 4.1):
501 // An lvalue (3.10) of a non-function, non-array type T can be
502 // converted to an rvalue.
503 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
504 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor45014fd2008-11-10 20:40:00 +0000505 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000506 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000507 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000508
509 // If T is a non-class type, the type of the rvalue is the
510 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorfcb19192009-02-11 23:02:49 +0000511 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
512 // just strip the qualifiers because they don't matter.
513
514 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000515 FromType = FromType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000516 } else if (FromType->isArrayType()) {
517 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000518 SCS.First = ICK_Array_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000519
520 // An lvalue or rvalue of type "array of N T" or "array of unknown
521 // bound of T" can be converted to an rvalue of type "pointer to
522 // T" (C++ 4.2p1).
523 FromType = Context.getArrayDecayedType(FromType);
524
525 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
526 // This conversion is deprecated. (C++ D.4).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000527 SCS.Deprecated = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000528
529 // For the purpose of ranking in overload resolution
530 // (13.3.3.1.1), this conversion is considered an
531 // array-to-pointer conversion followed by a qualification
532 // conversion (4.4). (C++ 4.2p2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000533 SCS.Second = ICK_Identity;
534 SCS.Third = ICK_Qualification;
535 SCS.ToTypePtr = ToType.getAsOpaquePtr();
536 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000537 }
Mike Stump90fc78e2009-08-04 21:02:39 +0000538 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
539 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000540 SCS.First = ICK_Function_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000541
542 // An lvalue of function type T can be converted to an rvalue of
543 // type "pointer to T." The result is a pointer to the
544 // function. (C++ 4.3p1).
545 FromType = Context.getPointerType(FromType);
Mike Stump90fc78e2009-08-04 21:02:39 +0000546 } else if (FunctionDecl *Fn
Douglas Gregor45014fd2008-11-10 20:40:00 +0000547 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000548 // Address of overloaded function (C++ [over.over]).
Douglas Gregor45014fd2008-11-10 20:40:00 +0000549 SCS.First = ICK_Function_To_Pointer;
550
551 // We were able to resolve the address of the overloaded function,
552 // so we can convert to the type of that function.
553 FromType = Fn->getType();
Sebastian Redlce6fff02009-03-16 23:22:08 +0000554 if (ToType->isLValueReferenceType())
555 FromType = Context.getLValueReferenceType(FromType);
556 else if (ToType->isRValueReferenceType())
557 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl7434fc32009-02-04 21:23:32 +0000558 else if (ToType->isMemberPointerType()) {
559 // Resolve address only succeeds if both sides are member pointers,
560 // but it doesn't have to be the same class. See DR 247.
561 // Note that this means that the type of &Derived::fn can be
562 // Ret (Base::*)(Args) if the fn overload actually found is from the
563 // base class, even if it was brought into the derived class via a
564 // using declaration. The standard isn't clear on this issue at all.
565 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
566 FromType = Context.getMemberPointerType(FromType,
567 Context.getTypeDeclType(M->getParent()).getTypePtr());
568 } else
Douglas Gregor45014fd2008-11-10 20:40:00 +0000569 FromType = Context.getPointerType(FromType);
Mike Stump90fc78e2009-08-04 21:02:39 +0000570 } else {
571 // We don't require any conversions for the first step.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000572 SCS.First = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000573 }
574
575 // The second conversion can be an integral promotion, floating
576 // point promotion, integral conversion, floating point conversion,
577 // floating-integral conversion, pointer conversion,
578 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorfcb19192009-02-11 23:02:49 +0000579 // For overloading in C, this can also be a "compatible-type"
580 // conversion.
Douglas Gregor6fd35572008-12-19 17:40:08 +0000581 bool IncompatibleObjC = false;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000582 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000583 // The unqualified versions of the types are the same: there's no
584 // conversion to do.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000585 SCS.Second = ICK_Identity;
Mike Stump90fc78e2009-08-04 21:02:39 +0000586 } else if (IsIntegralPromotion(From, FromType, ToType)) {
587 // Integral promotion (C++ 4.5).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000588 SCS.Second = ICK_Integral_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000589 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000590 } else if (IsFloatingPointPromotion(FromType, ToType)) {
591 // Floating point promotion (C++ 4.6).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000592 SCS.Second = ICK_Floating_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000593 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000594 } else if (IsComplexPromotion(FromType, ToType)) {
595 // Complex promotion (Clang extension)
Douglas Gregore819caf2009-02-12 00:15:05 +0000596 SCS.Second = ICK_Complex_Promotion;
597 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000598 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000599 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000600 // Integral conversions (C++ 4.7).
601 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000602 SCS.Second = ICK_Integral_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000603 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000604 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
605 // Floating point conversions (C++ 4.8).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000606 SCS.Second = ICK_Floating_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000607 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000608 } else if (FromType->isComplexType() && ToType->isComplexType()) {
609 // Complex conversions (C99 6.3.1.6)
Douglas Gregore819caf2009-02-12 00:15:05 +0000610 SCS.Second = ICK_Complex_Conversion;
611 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000612 } else if ((FromType->isFloatingType() &&
613 ToType->isIntegralType() && (!ToType->isBooleanType() &&
614 !ToType->isEnumeralType())) ||
615 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
616 ToType->isFloatingType())) {
617 // Floating-integral conversions (C++ 4.9).
618 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000619 SCS.Second = ICK_Floating_Integral;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000620 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000621 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
622 (ToType->isComplexType() && FromType->isArithmeticType())) {
623 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregore819caf2009-02-12 00:15:05 +0000624 SCS.Second = ICK_Complex_Real;
625 FromType = ToType.getUnqualifiedType();
Anders Carlsson8e4c1692009-08-28 15:33:32 +0000626 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
627 FromType, IncompatibleObjC)) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000628 // Pointer conversions (C++ 4.10).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000629 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000630 SCS.IncompatibleObjC = IncompatibleObjC;
Mike Stump90fc78e2009-08-04 21:02:39 +0000631 } else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
632 // Pointer to member conversions (4.11).
Sebastian Redlba387562009-01-25 19:43:20 +0000633 SCS.Second = ICK_Pointer_Member;
Mike Stump90fc78e2009-08-04 21:02:39 +0000634 } else if (ToType->isBooleanType() &&
635 (FromType->isArithmeticType() ||
636 FromType->isEnumeralType() ||
637 FromType->isPointerType() ||
638 FromType->isBlockPointerType() ||
639 FromType->isMemberPointerType() ||
640 FromType->isNullPtrType())) {
641 // Boolean conversions (C++ 4.12).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000642 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000643 FromType = Context.BoolTy;
Mike Stump90fc78e2009-08-04 21:02:39 +0000644 } else if (!getLangOptions().CPlusPlus &&
645 Context.typesAreCompatible(ToType, FromType)) {
646 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorfcb19192009-02-11 23:02:49 +0000647 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000648 } else {
649 // No second conversion required.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000650 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000651 }
652
Douglas Gregor81c29152008-10-29 00:13:59 +0000653 QualType CanonFrom;
654 QualType CanonTo;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000655 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000656 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000657 SCS.Third = ICK_Qualification;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000658 FromType = ToType;
Douglas Gregor81c29152008-10-29 00:13:59 +0000659 CanonFrom = Context.getCanonicalType(FromType);
660 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000661 } else {
662 // No conversion required
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000663 SCS.Third = ICK_Identity;
664
665 // C++ [over.best.ics]p6:
666 // [...] Any difference in top-level cv-qualification is
667 // subsumed by the initialization itself and does not constitute
668 // a conversion. [...]
Douglas Gregor81c29152008-10-29 00:13:59 +0000669 CanonFrom = Context.getCanonicalType(FromType);
670 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000671 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor81c29152008-10-29 00:13:59 +0000672 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
673 FromType = ToType;
674 CanonFrom = CanonTo;
675 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000676 }
677
678 // If we have not converted the argument type to the parameter type,
679 // this is a bad conversion sequence.
Douglas Gregor81c29152008-10-29 00:13:59 +0000680 if (CanonFrom != CanonTo)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000681 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000682
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000683 SCS.ToTypePtr = FromType.getAsOpaquePtr();
684 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000685}
686
687/// IsIntegralPromotion - Determines whether the conversion from the
688/// expression From (whose potentially-adjusted type is FromType) to
689/// ToType is an integral promotion (C++ 4.5). If so, returns true and
690/// sets PromotedType to the promoted type.
691bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
692{
693 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redl12aee862008-11-04 15:59:10 +0000694 // All integers are built-in.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000695 if (!To) {
696 return false;
697 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000698
699 // An rvalue of type char, signed char, unsigned char, short int, or
700 // unsigned short int can be converted to an rvalue of type int if
701 // int can represent all the values of the source type; otherwise,
702 // the source rvalue can be converted to an rvalue of type unsigned
703 // int (C++ 4.5p1).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000704 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000705 if (// We can promote any signed, promotable integer type to an int
706 (FromType->isSignedIntegerType() ||
707 // We can promote any unsigned integer type whose size is
708 // less than int to an int.
709 (!FromType->isSignedIntegerType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000710 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000711 return To->getKind() == BuiltinType::Int;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000712 }
713
Douglas Gregord2baafd2008-10-21 16:13:35 +0000714 return To->getKind() == BuiltinType::UInt;
715 }
716
717 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
718 // can be converted to an rvalue of the first of the following types
719 // that can represent all the values of its underlying type: int,
720 // unsigned int, long, or unsigned long (C++ 4.5p2).
721 if ((FromType->isEnumeralType() || FromType->isWideCharType())
722 && ToType->isIntegerType()) {
723 // Determine whether the type we're converting from is signed or
724 // unsigned.
725 bool FromIsSigned;
726 uint64_t FromSize = Context.getTypeSize(FromType);
727 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
728 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
729 FromIsSigned = UnderlyingType->isSignedIntegerType();
730 } else {
731 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
732 FromIsSigned = true;
733 }
734
735 // The types we'll try to promote to, in the appropriate
736 // order. Try each of these types.
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000737 QualType PromoteTypes[6] = {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000738 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000739 Context.LongTy, Context.UnsignedLongTy ,
740 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregord2baafd2008-10-21 16:13:35 +0000741 };
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000742 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000743 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
744 if (FromSize < ToSize ||
745 (FromSize == ToSize &&
746 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
747 // We found the type that we can promote to. If this is the
748 // type we wanted, we have a promotion. Otherwise, no
749 // promotion.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000750 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregord2baafd2008-10-21 16:13:35 +0000751 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
752 }
753 }
754 }
755
756 // An rvalue for an integral bit-field (9.6) can be converted to an
757 // rvalue of type int if int can represent all the values of the
758 // bit-field; otherwise, it can be converted to unsigned int if
759 // unsigned int can represent all the values of the bit-field. If
760 // the bit-field is larger yet, no integral promotion applies to
761 // it. If the bit-field has an enumerated type, it is treated as any
762 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stumpe127ae32009-05-16 07:39:55 +0000763 // FIXME: We should delay checking of bit-fields until we actually perform the
764 // conversion.
Douglas Gregor531434b2009-05-02 02:18:30 +0000765 using llvm::APSInt;
766 if (From)
767 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor82d44772008-12-20 23:49:58 +0000768 APSInt BitWidth;
Douglas Gregor531434b2009-05-02 02:18:30 +0000769 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
770 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
771 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
772 ToSize = Context.getTypeSize(ToType);
Douglas Gregor82d44772008-12-20 23:49:58 +0000773
774 // Are we promoting to an int from a bitfield that fits in an int?
775 if (BitWidth < ToSize ||
776 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
777 return To->getKind() == BuiltinType::Int;
778 }
779
780 // Are we promoting to an unsigned int from an unsigned bitfield
781 // that fits into an unsigned int?
782 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
783 return To->getKind() == BuiltinType::UInt;
784 }
785
786 return false;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000787 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000788 }
Douglas Gregor531434b2009-05-02 02:18:30 +0000789
Douglas Gregord2baafd2008-10-21 16:13:35 +0000790 // An rvalue of type bool can be converted to an rvalue of type int,
791 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000792 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000793 return true;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000794 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000795
796 return false;
797}
798
799/// IsFloatingPointPromotion - Determines whether the conversion from
800/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
801/// returns true and sets PromotedType to the promoted type.
802bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
803{
804 /// An rvalue of type float can be converted to an rvalue of type
805 /// double. (C++ 4.6p1).
806 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregore819caf2009-02-12 00:15:05 +0000807 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000808 if (FromBuiltin->getKind() == BuiltinType::Float &&
809 ToBuiltin->getKind() == BuiltinType::Double)
810 return true;
811
Douglas Gregore819caf2009-02-12 00:15:05 +0000812 // C99 6.3.1.5p1:
813 // When a float is promoted to double or long double, or a
814 // double is promoted to long double [...].
815 if (!getLangOptions().CPlusPlus &&
816 (FromBuiltin->getKind() == BuiltinType::Float ||
817 FromBuiltin->getKind() == BuiltinType::Double) &&
818 (ToBuiltin->getKind() == BuiltinType::LongDouble))
819 return true;
820 }
821
Douglas Gregord2baafd2008-10-21 16:13:35 +0000822 return false;
823}
824
Douglas Gregore819caf2009-02-12 00:15:05 +0000825/// \brief Determine if a conversion is a complex promotion.
826///
827/// A complex promotion is defined as a complex -> complex conversion
828/// where the conversion between the underlying real types is a
Douglas Gregor4ff48512009-02-12 00:26:06 +0000829/// floating-point or integral promotion.
Douglas Gregore819caf2009-02-12 00:15:05 +0000830bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
831 const ComplexType *FromComplex = FromType->getAsComplexType();
832 if (!FromComplex)
833 return false;
834
835 const ComplexType *ToComplex = ToType->getAsComplexType();
836 if (!ToComplex)
837 return false;
838
839 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor4ff48512009-02-12 00:26:06 +0000840 ToComplex->getElementType()) ||
841 IsIntegralPromotion(0, FromComplex->getElementType(),
842 ToComplex->getElementType());
Douglas Gregore819caf2009-02-12 00:15:05 +0000843}
844
Douglas Gregor24a90a52008-11-26 23:31:11 +0000845/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
846/// the pointer type FromPtr to a pointer to type ToPointee, with the
847/// same type qualifiers as FromPtr has on its pointee type. ToType,
848/// if non-empty, will be a pointer to ToType that may or may not have
849/// the right set of qualifiers on its pointee.
850static QualType
851BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
852 QualType ToPointee, QualType ToType,
853 ASTContext &Context) {
854 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
855 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
856 unsigned Quals = CanonFromPointee.getCVRQualifiers();
857
858 // Exact qualifier match -> return the pointer type we're converting to.
859 if (CanonToPointee.getCVRQualifiers() == Quals) {
860 // ToType is exactly what we need. Return it.
861 if (ToType.getTypePtr())
862 return ToType;
863
864 // Build a pointer to ToPointee. It has the right qualifiers
865 // already.
866 return Context.getPointerType(ToPointee);
867 }
868
869 // Just build a canonical type that has the right qualifiers.
870 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
871}
872
Anders Carlsson1e901552009-08-28 15:55:56 +0000873static bool isNullPointerConstantForConversion(Expr *Expr,
874 bool InOverloadResolution,
875 ASTContext &Context) {
876 // Handle value-dependent integral null pointer constants correctly.
877 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
878 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
879 Expr->getType()->isIntegralType())
880 return !InOverloadResolution;
881
882 return Expr->isNullPointerConstant(Context);
883}
884
Douglas Gregord2baafd2008-10-21 16:13:35 +0000885/// IsPointerConversion - Determines whether the conversion of the
886/// expression From, which has the (possibly adjusted) type FromType,
887/// can be converted to the type ToType via a pointer conversion (C++
888/// 4.10). If so, returns true and places the converted type (that
889/// might differ from ToType in its cv-qualifiers at some level) into
890/// ConvertedType.
Douglas Gregor9036ef72008-11-27 00:15:41 +0000891///
Douglas Gregor3f5a00c2008-11-27 01:19:21 +0000892/// This routine also supports conversions to and from block pointers
893/// and conversions with Objective-C's 'id', 'id<protocols...>', and
894/// pointers to interfaces. FIXME: Once we've determined the
895/// appropriate overloading rules for Objective-C, we may want to
896/// split the Objective-C checks into a different routine; however,
897/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor6fd35572008-12-19 17:40:08 +0000898/// conversions, so for now they live here. IncompatibleObjC will be
899/// set if the conversion is an allowed Objective-C conversion that
900/// should result in a warning.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000901bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson8e4c1692009-08-28 15:33:32 +0000902 bool InOverloadResolution,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000903 QualType& ConvertedType,
904 bool &IncompatibleObjC)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000905{
Douglas Gregor6fd35572008-12-19 17:40:08 +0000906 IncompatibleObjC = false;
Douglas Gregor932778b2008-12-19 19:13:09 +0000907 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
908 return true;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000909
Douglas Gregorf1d75712008-12-22 20:51:52 +0000910 // Conversion from a null pointer constant to any Objective-C pointer type.
Steve Naroffad75bd22009-07-16 15:41:00 +0000911 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson1e901552009-08-28 15:55:56 +0000912 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregorf1d75712008-12-22 20:51:52 +0000913 ConvertedType = ToType;
914 return true;
915 }
916
Douglas Gregor9036ef72008-11-27 00:15:41 +0000917 // Blocks: Block pointers can be converted to void*.
918 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000919 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor9036ef72008-11-27 00:15:41 +0000920 ConvertedType = ToType;
921 return true;
922 }
923 // Blocks: A null pointer constant can be converted to a block
924 // pointer type.
Anders Carlsson1e901552009-08-28 15:55:56 +0000925 if (ToType->isBlockPointerType() &&
926 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor9036ef72008-11-27 00:15:41 +0000927 ConvertedType = ToType;
928 return true;
929 }
930
Sebastian Redl5d0ead72009-05-10 18:38:11 +0000931 // If the left-hand-side is nullptr_t, the right side can be a null
932 // pointer constant.
Anders Carlsson1e901552009-08-28 15:55:56 +0000933 if (ToType->isNullPtrType() &&
934 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl5d0ead72009-05-10 18:38:11 +0000935 ConvertedType = ToType;
936 return true;
937 }
938
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000939 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregord2baafd2008-10-21 16:13:35 +0000940 if (!ToTypePtr)
941 return false;
942
943 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson1e901552009-08-28 15:55:56 +0000944 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000945 ConvertedType = ToType;
946 return true;
947 }
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000948
Douglas Gregor24a90a52008-11-26 23:31:11 +0000949 // Beyond this point, both types need to be pointers.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000950 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor24a90a52008-11-26 23:31:11 +0000951 if (!FromTypePtr)
952 return false;
953
954 QualType FromPointeeType = FromTypePtr->getPointeeType();
955 QualType ToPointeeType = ToTypePtr->getPointeeType();
956
Douglas Gregord2baafd2008-10-21 16:13:35 +0000957 // An rvalue of type "pointer to cv T," where T is an object type,
958 // can be converted to an rvalue of type "pointer to cv void" (C++
959 // 4.10p2).
Douglas Gregor26ea1222009-03-24 20:32:41 +0000960 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000961 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
962 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000963 ToType, Context);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000964 return true;
965 }
966
Douglas Gregorfcb19192009-02-11 23:02:49 +0000967 // When we're overloading in C, we allow a special kind of pointer
968 // conversion for compatible-but-not-identical pointee types.
969 if (!getLangOptions().CPlusPlus &&
970 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
971 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
972 ToPointeeType,
973 ToType, Context);
974 return true;
975 }
976
Douglas Gregor14046502008-10-23 00:40:37 +0000977 // C++ [conv.ptr]p3:
978 //
979 // An rvalue of type "pointer to cv D," where D is a class type,
980 // can be converted to an rvalue of type "pointer to cv B," where
981 // B is a base class (clause 10) of D. If B is an inaccessible
982 // (clause 11) or ambiguous (10.2) base class of D, a program that
983 // necessitates this conversion is ill-formed. The result of the
984 // conversion is a pointer to the base class sub-object of the
985 // derived class object. The null pointer value is converted to
986 // the null pointer value of the destination type.
987 //
Douglas Gregorbb461502008-10-24 04:54:22 +0000988 // Note that we do not check for ambiguity or inaccessibility
989 // here. That is handled by CheckPointerConversion.
Douglas Gregorfcb19192009-02-11 23:02:49 +0000990 if (getLangOptions().CPlusPlus &&
991 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor24a90a52008-11-26 23:31:11 +0000992 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000993 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
994 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000995 ToType, Context);
996 return true;
997 }
Douglas Gregor14046502008-10-23 00:40:37 +0000998
Douglas Gregor932778b2008-12-19 19:13:09 +0000999 return false;
1000}
1001
1002/// isObjCPointerConversion - Determines whether this is an
1003/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1004/// with the same arguments and return values.
1005bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
1006 QualType& ConvertedType,
1007 bool &IncompatibleObjC) {
1008 if (!getLangOptions().ObjC1)
1009 return false;
1010
Steve Naroff329ec222009-07-10 23:34:53 +00001011 // First, we handle all conversions on ObjC object pointer types.
1012 const ObjCObjectPointerType* ToObjCPtr = ToType->getAsObjCObjectPointerType();
1013 const ObjCObjectPointerType *FromObjCPtr =
1014 FromType->getAsObjCObjectPointerType();
Douglas Gregor932778b2008-12-19 19:13:09 +00001015
Steve Naroff329ec222009-07-10 23:34:53 +00001016 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff7bffd372009-07-15 18:40:39 +00001017 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff329ec222009-07-10 23:34:53 +00001018 // pointer to any interface (in both directions).
Steve Naroff7bffd372009-07-15 18:40:39 +00001019 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00001020 ConvertedType = ToType;
1021 return true;
1022 }
1023 // Conversions with Objective-C's id<...>.
1024 if ((FromObjCPtr->isObjCQualifiedIdType() ||
1025 ToObjCPtr->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00001026 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
1027 /*compare=*/false)) {
Steve Naroff329ec222009-07-10 23:34:53 +00001028 ConvertedType = ToType;
1029 return true;
1030 }
1031 // Objective C++: We're able to convert from a pointer to an
1032 // interface to a pointer to a different interface.
1033 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1034 ConvertedType = ToType;
1035 return true;
1036 }
1037
1038 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1039 // Okay: this is some kind of implicit downcast of Objective-C
1040 // interfaces, which is permitted. However, we're going to
1041 // complain about it.
1042 IncompatibleObjC = true;
1043 ConvertedType = FromType;
1044 return true;
1045 }
1046 }
1047 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor80402cf2008-12-23 00:53:59 +00001048 QualType ToPointeeType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001049 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff329ec222009-07-10 23:34:53 +00001050 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001051 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor80402cf2008-12-23 00:53:59 +00001052 ToPointeeType = ToBlockPtr->getPointeeType();
1053 else
Douglas Gregor932778b2008-12-19 19:13:09 +00001054 return false;
1055
Douglas Gregor80402cf2008-12-23 00:53:59 +00001056 QualType FromPointeeType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001057 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff329ec222009-07-10 23:34:53 +00001058 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001059 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor80402cf2008-12-23 00:53:59 +00001060 FromPointeeType = FromBlockPtr->getPointeeType();
1061 else
Douglas Gregor932778b2008-12-19 19:13:09 +00001062 return false;
1063
Douglas Gregor932778b2008-12-19 19:13:09 +00001064 // If we have pointers to pointers, recursively check whether this
1065 // is an Objective-C conversion.
1066 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1067 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1068 IncompatibleObjC)) {
1069 // We always complain about this conversion.
1070 IncompatibleObjC = true;
1071 ConvertedType = ToType;
1072 return true;
1073 }
Douglas Gregor80402cf2008-12-23 00:53:59 +00001074 // If we have pointers to functions or blocks, check whether the only
Douglas Gregor932778b2008-12-19 19:13:09 +00001075 // differences in the argument and result types are in Objective-C
1076 // pointer conversions. If so, we permit the conversion (but
1077 // complain about it).
Douglas Gregor4fa58902009-02-26 23:50:07 +00001078 const FunctionProtoType *FromFunctionType
1079 = FromPointeeType->getAsFunctionProtoType();
1080 const FunctionProtoType *ToFunctionType
1081 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregor932778b2008-12-19 19:13:09 +00001082 if (FromFunctionType && ToFunctionType) {
1083 // If the function types are exactly the same, this isn't an
1084 // Objective-C pointer conversion.
1085 if (Context.getCanonicalType(FromPointeeType)
1086 == Context.getCanonicalType(ToPointeeType))
1087 return false;
1088
1089 // Perform the quick checks that will tell us whether these
1090 // function types are obviously different.
1091 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1092 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1093 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1094 return false;
1095
1096 bool HasObjCConversion = false;
1097 if (Context.getCanonicalType(FromFunctionType->getResultType())
1098 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1099 // Okay, the types match exactly. Nothing to do.
1100 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1101 ToFunctionType->getResultType(),
1102 ConvertedType, IncompatibleObjC)) {
1103 // Okay, we have an Objective-C pointer conversion.
1104 HasObjCConversion = true;
1105 } else {
1106 // Function types are too different. Abort.
1107 return false;
1108 }
1109
1110 // Check argument types.
1111 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1112 ArgIdx != NumArgs; ++ArgIdx) {
1113 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1114 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1115 if (Context.getCanonicalType(FromArgType)
1116 == Context.getCanonicalType(ToArgType)) {
1117 // Okay, the types match exactly. Nothing to do.
1118 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1119 ConvertedType, IncompatibleObjC)) {
1120 // Okay, we have an Objective-C pointer conversion.
1121 HasObjCConversion = true;
1122 } else {
1123 // Argument types are too different. Abort.
1124 return false;
1125 }
1126 }
1127
1128 if (HasObjCConversion) {
1129 // We had an Objective-C conversion. Allow this pointer
1130 // conversion, but complain about it.
1131 ConvertedType = ToType;
1132 IncompatibleObjC = true;
1133 return true;
1134 }
1135 }
1136
Sebastian Redlba387562009-01-25 19:43:20 +00001137 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001138}
1139
Douglas Gregorbb461502008-10-24 04:54:22 +00001140/// CheckPointerConversion - Check the pointer conversion from the
1141/// expression From to the type ToType. This routine checks for
Sebastian Redl0e35d042009-07-25 15:41:38 +00001142/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregorbb461502008-10-24 04:54:22 +00001143/// conversions for which IsPointerConversion has already returned
1144/// true. It returns true and produces a diagnostic if there was an
1145/// error, or returns false otherwise.
1146bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1147 QualType FromType = From->getType();
1148
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001149 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1150 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregorbb461502008-10-24 04:54:22 +00001151 QualType FromPointeeType = FromPtrType->getPointeeType(),
1152 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregord0c653a2008-12-18 23:43:31 +00001153
Douglas Gregorbb461502008-10-24 04:54:22 +00001154 if (FromPointeeType->isRecordType() &&
1155 ToPointeeType->isRecordType()) {
1156 // We must have a derived-to-base conversion. Check an
1157 // ambiguous or inaccessible conversion.
Douglas Gregor651d1cc2008-10-24 16:17:19 +00001158 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1159 From->getExprLoc(),
1160 From->getSourceRange());
Douglas Gregorbb461502008-10-24 04:54:22 +00001161 }
1162 }
Steve Naroff329ec222009-07-10 23:34:53 +00001163 if (const ObjCObjectPointerType *FromPtrType =
1164 FromType->getAsObjCObjectPointerType())
1165 if (const ObjCObjectPointerType *ToPtrType =
1166 ToType->getAsObjCObjectPointerType()) {
1167 // Objective-C++ conversions are always okay.
1168 // FIXME: We should have a different class of conversions for the
1169 // Objective-C++ implicit conversions.
Steve Naroff7bffd372009-07-15 18:40:39 +00001170 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff329ec222009-07-10 23:34:53 +00001171 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +00001172
Steve Naroff329ec222009-07-10 23:34:53 +00001173 }
Douglas Gregorbb461502008-10-24 04:54:22 +00001174 return false;
1175}
1176
Sebastian Redlba387562009-01-25 19:43:20 +00001177/// IsMemberPointerConversion - Determines whether the conversion of the
1178/// expression From, which has the (possibly adjusted) type FromType, can be
1179/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1180/// If so, returns true and places the converted type (that might differ from
1181/// ToType in its cv-qualifiers at some level) into ConvertedType.
1182bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1183 QualType ToType, QualType &ConvertedType)
1184{
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001185 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redlba387562009-01-25 19:43:20 +00001186 if (!ToTypePtr)
1187 return false;
1188
1189 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1190 if (From->isNullPointerConstant(Context)) {
1191 ConvertedType = ToType;
1192 return true;
1193 }
1194
1195 // Otherwise, both types have to be member pointers.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001196 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redlba387562009-01-25 19:43:20 +00001197 if (!FromTypePtr)
1198 return false;
1199
1200 // A pointer to member of B can be converted to a pointer to member of D,
1201 // where D is derived from B (C++ 4.11p2).
1202 QualType FromClass(FromTypePtr->getClass(), 0);
1203 QualType ToClass(ToTypePtr->getClass(), 0);
1204 // FIXME: What happens when these are dependent? Is this function even called?
1205
1206 if (IsDerivedFrom(ToClass, FromClass)) {
1207 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1208 ToClass.getTypePtr());
1209 return true;
1210 }
1211
1212 return false;
1213}
1214
1215/// CheckMemberPointerConversion - Check the member pointer conversion from the
1216/// expression From to the type ToType. This routine checks for ambiguous or
1217/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1218/// for which IsMemberPointerConversion has already returned true. It returns
1219/// true and produces a diagnostic if there was an error, or returns false
1220/// otherwise.
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001221bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
1222 CastExpr::CastKind &Kind) {
Sebastian Redlba387562009-01-25 19:43:20 +00001223 QualType FromType = From->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001224 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001225 if (!FromPtrType) {
1226 // This must be a null pointer to member pointer conversion
1227 assert(From->isNullPointerConstant(Context) &&
1228 "Expr must be null pointer constant!");
1229 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001230 return false;
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001231 }
Sebastian Redlba387562009-01-25 19:43:20 +00001232
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001233 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001234 assert(ToPtrType && "No member pointer cast has a target type "
1235 "that is not a member pointer.");
Sebastian Redlba387562009-01-25 19:43:20 +00001236
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001237 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1238 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redlba387562009-01-25 19:43:20 +00001239
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001240 // FIXME: What about dependent types?
1241 assert(FromClass->isRecordType() && "Pointer into non-class.");
1242 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redlba387562009-01-25 19:43:20 +00001243
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001244 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1245 /*DetectVirtual=*/true);
1246 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1247 assert(DerivationOkay &&
1248 "Should not have been called if derivation isn't OK.");
1249 (void)DerivationOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001250
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001251 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1252 getUnqualifiedType())) {
1253 // Derivation is ambiguous. Redo the check to find the exact paths.
1254 Paths.clear();
1255 Paths.setRecordingPaths(true);
1256 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1257 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1258 (void)StillOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001259
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001260 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1261 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1262 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1263 return true;
Sebastian Redlba387562009-01-25 19:43:20 +00001264 }
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001265
Douglas Gregor2e047592009-02-28 01:32:25 +00001266 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001267 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1268 << FromClass << ToClass << QualType(VBase, 0)
1269 << From->getSourceRange();
1270 return true;
1271 }
1272
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001273 // Must be a base to derived member conversion.
1274 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redlba387562009-01-25 19:43:20 +00001275 return false;
1276}
1277
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001278/// IsQualificationConversion - Determines whether the conversion from
1279/// an rvalue of type FromType to ToType is a qualification conversion
1280/// (C++ 4.4).
1281bool
1282Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1283{
1284 FromType = Context.getCanonicalType(FromType);
1285 ToType = Context.getCanonicalType(ToType);
1286
1287 // If FromType and ToType are the same type, this is not a
1288 // qualification conversion.
1289 if (FromType == ToType)
1290 return false;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001291
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001292 // (C++ 4.4p4):
1293 // A conversion can add cv-qualifiers at levels other than the first
1294 // in multi-level pointers, subject to the following rules: [...]
1295 bool PreviousToQualsIncludeConst = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001296 bool UnwrappedAnyPointer = false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001297 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001298 // Within each iteration of the loop, we check the qualifiers to
1299 // determine if this still looks like a qualification
1300 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001301 // pointers or pointers-to-members and do it all again
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001302 // until there are no more pointers or pointers-to-members left to
1303 // unwrap.
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001304 UnwrappedAnyPointer = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001305
1306 // -- for every j > 0, if const is in cv 1,j then const is in cv
1307 // 2,j, and similarly for volatile.
Douglas Gregore5db4f72008-10-22 00:38:21 +00001308 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001309 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001310
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001311 // -- if the cv 1,j and cv 2,j are different, then const is in
1312 // every cv for 0 < k < j.
1313 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001314 && !PreviousToQualsIncludeConst)
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001315 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001316
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001317 // Keep track of whether all prior cv-qualifiers in the "to" type
1318 // include const.
1319 PreviousToQualsIncludeConst
1320 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001321 }
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001322
1323 // We are left with FromType and ToType being the pointee types
1324 // after unwrapping the original FromType and ToType the same number
1325 // of types. If we unwrapped any pointers, and if FromType and
1326 // ToType have the same unqualified type (since we checked
1327 // qualifiers above), then this is a qualification conversion.
1328 return UnwrappedAnyPointer &&
1329 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1330}
1331
Douglas Gregor8c860df2009-08-21 23:19:43 +00001332/// \brief Given a function template or function, extract the function template
1333/// declaration (if any) and the underlying function declaration.
1334template<typename T>
1335static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1336 FunctionTemplateDecl *&FunctionTemplate) {
1337 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1338 if (FunctionTemplate)
1339 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1340 else
1341 Function = cast<T>(Orig);
1342}
1343
1344
Douglas Gregorb206cc42009-01-30 23:27:23 +00001345/// Determines whether there is a user-defined conversion sequence
1346/// (C++ [over.ics.user]) that converts expression From to the type
1347/// ToType. If such a conversion exists, User will contain the
1348/// user-defined conversion sequence that performs such a conversion
1349/// and this routine will return true. Otherwise, this routine returns
1350/// false and User is unspecified.
1351///
1352/// \param AllowConversionFunctions true if the conversion should
1353/// consider conversion functions at all. If false, only constructors
1354/// will be considered.
1355///
1356/// \param AllowExplicit true if the conversion should consider C++0x
1357/// "explicit" conversion functions as well as non-explicit conversion
1358/// functions (C++0x [class.conv.fct]p2).
Sebastian Redla55834a2009-04-12 17:16:29 +00001359///
1360/// \param ForceRValue true if the expression should be treated as an rvalue
1361/// for overload resolution.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001362bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001363 UserDefinedConversionSequence& User,
Douglas Gregorb206cc42009-01-30 23:27:23 +00001364 bool AllowConversionFunctions,
Sebastian Redla55834a2009-04-12 17:16:29 +00001365 bool AllowExplicit, bool ForceRValue)
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001366{
1367 OverloadCandidateSet CandidateSet;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001368 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001369 if (CXXRecordDecl *ToRecordDecl
1370 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1371 // C++ [over.match.ctor]p1:
1372 // When objects of class type are direct-initialized (8.5), or
1373 // copy-initialized from an expression of the same or a
1374 // derived class type (8.5), overload resolution selects the
1375 // constructor. [...] For copy-initialization, the candidate
1376 // functions are all the converting constructors (12.3.1) of
1377 // that class. The argument list is the expression-list within
1378 // the parentheses of the initializer.
1379 DeclarationName ConstructorName
1380 = Context.DeclarationNames.getCXXConstructorName(
1381 Context.getCanonicalType(ToType).getUnqualifiedType());
1382 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001383 for (llvm::tie(Con, ConEnd)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001384 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor2e047592009-02-28 01:32:25 +00001385 Con != ConEnd; ++Con) {
Douglas Gregor050cabf2009-08-21 18:42:58 +00001386 // Find the constructor (which may be a template).
1387 CXXConstructorDecl *Constructor = 0;
1388 FunctionTemplateDecl *ConstructorTmpl
1389 = dyn_cast<FunctionTemplateDecl>(*Con);
1390 if (ConstructorTmpl)
1391 Constructor
1392 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1393 else
1394 Constructor = cast<CXXConstructorDecl>(*Con);
1395
Fariborz Jahanian625fb9d2009-08-06 17:22:51 +00001396 if (!Constructor->isInvalidDecl() &&
Anders Carlsson94894572009-08-28 16:57:08 +00001397 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor050cabf2009-08-21 18:42:58 +00001398 if (ConstructorTmpl)
1399 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
1400 1, CandidateSet,
1401 /*SuppressUserConversions=*/true,
1402 ForceRValue);
1403 else
1404 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1405 /*SuppressUserConversions=*/true, ForceRValue);
1406 }
Douglas Gregor2e047592009-02-28 01:32:25 +00001407 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001408 }
1409 }
1410
Douglas Gregorb206cc42009-01-30 23:27:23 +00001411 if (!AllowConversionFunctions) {
1412 // Don't allow any conversion functions to enter the overload set.
Anders Carlssona21e7872009-08-26 23:45:07 +00001413 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1414 PDiag(0)
1415 << From->getSourceRange())) {
Douglas Gregorb35c7992009-08-24 15:23:48 +00001416 // No conversion functions from incomplete types.
Douglas Gregor2e047592009-02-28 01:32:25 +00001417 } else if (const RecordType *FromRecordType
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001418 = From->getType()->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001419 if (CXXRecordDecl *FromRecordDecl
1420 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1421 // Add all of the conversion functions as candidates.
1422 // FIXME: Look for conversions in base classes!
1423 OverloadedFunctionDecl *Conversions
1424 = FromRecordDecl->getConversionFunctions();
1425 for (OverloadedFunctionDecl::function_iterator Func
1426 = Conversions->function_begin();
1427 Func != Conversions->function_end(); ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00001428 CXXConversionDecl *Conv;
1429 FunctionTemplateDecl *ConvTemplate;
1430 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1431 if (ConvTemplate)
1432 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1433 else
1434 Conv = dyn_cast<CXXConversionDecl>(*Func);
1435
1436 if (AllowExplicit || !Conv->isExplicit()) {
1437 if (ConvTemplate)
1438 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1439 CandidateSet);
1440 else
1441 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1442 }
Douglas Gregor2e047592009-02-28 01:32:25 +00001443 }
Douglas Gregor60714f92008-11-07 22:36:19 +00001444 }
1445 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001446
1447 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001448 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001449 case OR_Success:
1450 // Record the standard conversion we used and the conversion function.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001451 if (CXXConstructorDecl *Constructor
1452 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1453 // C++ [over.ics.user]p1:
1454 // If the user-defined conversion is specified by a
1455 // constructor (12.3.1), the initial standard conversion
1456 // sequence converts the source type to the type required by
1457 // the argument of the constructor.
1458 //
1459 // FIXME: What about ellipsis conversions?
1460 QualType ThisType = Constructor->getThisType(Context);
1461 User.Before = Best->Conversions[0].Standard;
1462 User.ConversionFunction = Constructor;
1463 User.After.setAsIdentityConversion();
1464 User.After.FromTypePtr
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001465 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001466 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1467 return true;
Douglas Gregor60714f92008-11-07 22:36:19 +00001468 } else if (CXXConversionDecl *Conversion
1469 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1470 // C++ [over.ics.user]p1:
1471 //
1472 // [...] If the user-defined conversion is specified by a
1473 // conversion function (12.3.2), the initial standard
1474 // conversion sequence converts the source type to the
1475 // implicit object parameter of the conversion function.
1476 User.Before = Best->Conversions[0].Standard;
1477 User.ConversionFunction = Conversion;
1478
1479 // C++ [over.ics.user]p2:
1480 // The second standard conversion sequence converts the
1481 // result of the user-defined conversion to the target type
1482 // for the sequence. Since an implicit conversion sequence
1483 // is an initialization, the special rules for
1484 // initialization by user-defined conversion apply when
1485 // selecting the best user-defined conversion for a
1486 // user-defined conversion sequence (see 13.3.3 and
1487 // 13.3.3.1).
1488 User.After = Best->FinalConversion;
1489 return true;
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001490 } else {
Douglas Gregor60714f92008-11-07 22:36:19 +00001491 assert(false && "Not a constructor or conversion function?");
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001492 return false;
1493 }
1494
1495 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00001496 case OR_Deleted:
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001497 // No conversion here! We're done.
1498 return false;
1499
1500 case OR_Ambiguous:
1501 // FIXME: See C++ [over.best.ics]p10 for the handling of
1502 // ambiguous conversion sequences.
1503 return false;
1504 }
1505
1506 return false;
1507}
1508
Douglas Gregord2baafd2008-10-21 16:13:35 +00001509/// CompareImplicitConversionSequences - Compare two implicit
1510/// conversion sequences to determine whether one is better than the
1511/// other or if they are indistinguishable (C++ 13.3.3.2).
1512ImplicitConversionSequence::CompareKind
1513Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1514 const ImplicitConversionSequence& ICS2)
1515{
1516 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1517 // conversion sequences (as defined in 13.3.3.1)
1518 // -- a standard conversion sequence (13.3.3.1.1) is a better
1519 // conversion sequence than a user-defined conversion sequence or
1520 // an ellipsis conversion sequence, and
1521 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1522 // conversion sequence than an ellipsis conversion sequence
1523 // (13.3.3.1.3).
1524 //
1525 if (ICS1.ConversionKind < ICS2.ConversionKind)
1526 return ImplicitConversionSequence::Better;
1527 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1528 return ImplicitConversionSequence::Worse;
1529
1530 // Two implicit conversion sequences of the same form are
1531 // indistinguishable conversion sequences unless one of the
1532 // following rules apply: (C++ 13.3.3.2p3):
1533 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1534 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1535 else if (ICS1.ConversionKind ==
1536 ImplicitConversionSequence::UserDefinedConversion) {
1537 // User-defined conversion sequence U1 is a better conversion
1538 // sequence than another user-defined conversion sequence U2 if
1539 // they contain the same user-defined conversion function or
1540 // constructor and if the second standard conversion sequence of
1541 // U1 is better than the second standard conversion sequence of
1542 // U2 (C++ 13.3.3.2p3).
1543 if (ICS1.UserDefined.ConversionFunction ==
1544 ICS2.UserDefined.ConversionFunction)
1545 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1546 ICS2.UserDefined.After);
1547 }
1548
1549 return ImplicitConversionSequence::Indistinguishable;
1550}
1551
1552/// CompareStandardConversionSequences - Compare two standard
1553/// conversion sequences to determine whether one is better than the
1554/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1555ImplicitConversionSequence::CompareKind
1556Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1557 const StandardConversionSequence& SCS2)
1558{
1559 // Standard conversion sequence S1 is a better conversion sequence
1560 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1561
1562 // -- S1 is a proper subsequence of S2 (comparing the conversion
1563 // sequences in the canonical form defined by 13.3.3.1.1,
1564 // excluding any Lvalue Transformation; the identity conversion
1565 // sequence is considered to be a subsequence of any
1566 // non-identity conversion sequence) or, if not that,
1567 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1568 // Neither is a proper subsequence of the other. Do nothing.
1569 ;
1570 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1571 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1572 (SCS1.Second == ICK_Identity &&
1573 SCS1.Third == ICK_Identity))
1574 // SCS1 is a proper subsequence of SCS2.
1575 return ImplicitConversionSequence::Better;
1576 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1577 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1578 (SCS2.Second == ICK_Identity &&
1579 SCS2.Third == ICK_Identity))
1580 // SCS2 is a proper subsequence of SCS1.
1581 return ImplicitConversionSequence::Worse;
1582
1583 // -- the rank of S1 is better than the rank of S2 (by the rules
1584 // defined below), or, if not that,
1585 ImplicitConversionRank Rank1 = SCS1.getRank();
1586 ImplicitConversionRank Rank2 = SCS2.getRank();
1587 if (Rank1 < Rank2)
1588 return ImplicitConversionSequence::Better;
1589 else if (Rank2 < Rank1)
1590 return ImplicitConversionSequence::Worse;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001591
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001592 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1593 // are indistinguishable unless one of the following rules
1594 // applies:
1595
1596 // A conversion that is not a conversion of a pointer, or
1597 // pointer to member, to bool is better than another conversion
1598 // that is such a conversion.
1599 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1600 return SCS2.isPointerConversionToBool()
1601 ? ImplicitConversionSequence::Better
1602 : ImplicitConversionSequence::Worse;
1603
Douglas Gregor14046502008-10-23 00:40:37 +00001604 // C++ [over.ics.rank]p4b2:
1605 //
1606 // If class B is derived directly or indirectly from class A,
Douglas Gregor0e343382008-10-29 14:50:44 +00001607 // conversion of B* to A* is better than conversion of B* to
1608 // void*, and conversion of A* to void* is better than conversion
1609 // of B* to void*.
Douglas Gregor14046502008-10-23 00:40:37 +00001610 bool SCS1ConvertsToVoid
1611 = SCS1.isPointerConversionToVoidPointer(Context);
1612 bool SCS2ConvertsToVoid
1613 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregor0e343382008-10-29 14:50:44 +00001614 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1615 // Exactly one of the conversion sequences is a conversion to
1616 // a void pointer; it's the worse conversion.
Douglas Gregor14046502008-10-23 00:40:37 +00001617 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1618 : ImplicitConversionSequence::Worse;
Douglas Gregor0e343382008-10-29 14:50:44 +00001619 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1620 // Neither conversion sequence converts to a void pointer; compare
1621 // their derived-to-base conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001622 if (ImplicitConversionSequence::CompareKind DerivedCK
1623 = CompareDerivedToBaseConversions(SCS1, SCS2))
1624 return DerivedCK;
Douglas Gregor0e343382008-10-29 14:50:44 +00001625 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1626 // Both conversion sequences are conversions to void
1627 // pointers. Compare the source types to determine if there's an
1628 // inheritance relationship in their sources.
1629 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1630 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1631
1632 // Adjust the types we're converting from via the array-to-pointer
1633 // conversion, if we need to.
1634 if (SCS1.First == ICK_Array_To_Pointer)
1635 FromType1 = Context.getArrayDecayedType(FromType1);
1636 if (SCS2.First == ICK_Array_To_Pointer)
1637 FromType2 = Context.getArrayDecayedType(FromType2);
1638
1639 QualType FromPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001640 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor0e343382008-10-29 14:50:44 +00001641 QualType FromPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001642 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor0e343382008-10-29 14:50:44 +00001643
1644 if (IsDerivedFrom(FromPointee2, FromPointee1))
1645 return ImplicitConversionSequence::Better;
1646 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1647 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001648
1649 // Objective-C++: If one interface is more specific than the
1650 // other, it is the better one.
1651 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1652 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1653 if (FromIface1 && FromIface1) {
1654 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1655 return ImplicitConversionSequence::Better;
1656 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1657 return ImplicitConversionSequence::Worse;
1658 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001659 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001660
1661 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1662 // bullet 3).
Douglas Gregor14046502008-10-23 00:40:37 +00001663 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001664 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor14046502008-10-23 00:40:37 +00001665 return QualCK;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001666
Douglas Gregor0e343382008-10-29 14:50:44 +00001667 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001668 // C++0x [over.ics.rank]p3b4:
1669 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1670 // implicit object parameter of a non-static member function declared
1671 // without a ref-qualifier, and S1 binds an rvalue reference to an
1672 // rvalue and S2 binds an lvalue reference.
Sebastian Redldfc30332009-03-29 15:27:50 +00001673 // FIXME: We don't know if we're dealing with the implicit object parameter,
1674 // or if the member function in this case has a ref qualifier.
1675 // (Of course, we don't have ref qualifiers yet.)
1676 if (SCS1.RRefBinding != SCS2.RRefBinding)
1677 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1678 : ImplicitConversionSequence::Worse;
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001679
1680 // C++ [over.ics.rank]p3b4:
1681 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1682 // which the references refer are the same type except for
1683 // top-level cv-qualifiers, and the type to which the reference
1684 // initialized by S2 refers is more cv-qualified than the type
1685 // to which the reference initialized by S1 refers.
Sebastian Redldfc30332009-03-29 15:27:50 +00001686 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1687 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregor0e343382008-10-29 14:50:44 +00001688 T1 = Context.getCanonicalType(T1);
1689 T2 = Context.getCanonicalType(T2);
1690 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1691 if (T2.isMoreQualifiedThan(T1))
1692 return ImplicitConversionSequence::Better;
1693 else if (T1.isMoreQualifiedThan(T2))
1694 return ImplicitConversionSequence::Worse;
1695 }
1696 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001697
1698 return ImplicitConversionSequence::Indistinguishable;
1699}
1700
1701/// CompareQualificationConversions - Compares two standard conversion
1702/// sequences to determine whether they can be ranked based on their
1703/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1704ImplicitConversionSequence::CompareKind
1705Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1706 const StandardConversionSequence& SCS2)
1707{
Douglas Gregor4459bbe2008-10-22 15:04:37 +00001708 // C++ 13.3.3.2p3:
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001709 // -- S1 and S2 differ only in their qualification conversion and
1710 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1711 // cv-qualification signature of type T1 is a proper subset of
1712 // the cv-qualification signature of type T2, and S1 is not the
1713 // deprecated string literal array-to-pointer conversion (4.2).
1714 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1715 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1716 return ImplicitConversionSequence::Indistinguishable;
1717
1718 // FIXME: the example in the standard doesn't use a qualification
1719 // conversion (!)
1720 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1721 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1722 T1 = Context.getCanonicalType(T1);
1723 T2 = Context.getCanonicalType(T2);
1724
1725 // If the types are the same, we won't learn anything by unwrapped
1726 // them.
1727 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1728 return ImplicitConversionSequence::Indistinguishable;
1729
1730 ImplicitConversionSequence::CompareKind Result
1731 = ImplicitConversionSequence::Indistinguishable;
1732 while (UnwrapSimilarPointerTypes(T1, T2)) {
1733 // Within each iteration of the loop, we check the qualifiers to
1734 // determine if this still looks like a qualification
1735 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001736 // pointers or pointers-to-members and do it all again
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001737 // until there are no more pointers or pointers-to-members left
1738 // to unwrap. This essentially mimics what
1739 // IsQualificationConversion does, but here we're checking for a
1740 // strict subset of qualifiers.
1741 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1742 // The qualifiers are the same, so this doesn't tell us anything
1743 // about how the sequences rank.
1744 ;
1745 else if (T2.isMoreQualifiedThan(T1)) {
1746 // T1 has fewer qualifiers, so it could be the better sequence.
1747 if (Result == ImplicitConversionSequence::Worse)
1748 // Neither has qualifiers that are a subset of the other's
1749 // qualifiers.
1750 return ImplicitConversionSequence::Indistinguishable;
1751
1752 Result = ImplicitConversionSequence::Better;
1753 } else if (T1.isMoreQualifiedThan(T2)) {
1754 // T2 has fewer qualifiers, so it could be the better sequence.
1755 if (Result == ImplicitConversionSequence::Better)
1756 // Neither has qualifiers that are a subset of the other's
1757 // qualifiers.
1758 return ImplicitConversionSequence::Indistinguishable;
1759
1760 Result = ImplicitConversionSequence::Worse;
1761 } else {
1762 // Qualifiers are disjoint.
1763 return ImplicitConversionSequence::Indistinguishable;
1764 }
1765
1766 // If the types after this point are equivalent, we're done.
1767 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1768 break;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001769 }
1770
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001771 // Check that the winning standard conversion sequence isn't using
1772 // the deprecated string literal array to pointer conversion.
1773 switch (Result) {
1774 case ImplicitConversionSequence::Better:
1775 if (SCS1.Deprecated)
1776 Result = ImplicitConversionSequence::Indistinguishable;
1777 break;
1778
1779 case ImplicitConversionSequence::Indistinguishable:
1780 break;
1781
1782 case ImplicitConversionSequence::Worse:
1783 if (SCS2.Deprecated)
1784 Result = ImplicitConversionSequence::Indistinguishable;
1785 break;
1786 }
1787
1788 return Result;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001789}
1790
Douglas Gregor14046502008-10-23 00:40:37 +00001791/// CompareDerivedToBaseConversions - Compares two standard conversion
1792/// sequences to determine whether they can be ranked based on their
Douglas Gregor24a90a52008-11-26 23:31:11 +00001793/// various kinds of derived-to-base conversions (C++
1794/// [over.ics.rank]p4b3). As part of these checks, we also look at
1795/// conversions between Objective-C interface types.
Douglas Gregor14046502008-10-23 00:40:37 +00001796ImplicitConversionSequence::CompareKind
1797Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1798 const StandardConversionSequence& SCS2) {
1799 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1800 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1801 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1802 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1803
1804 // Adjust the types we're converting from via the array-to-pointer
1805 // conversion, if we need to.
1806 if (SCS1.First == ICK_Array_To_Pointer)
1807 FromType1 = Context.getArrayDecayedType(FromType1);
1808 if (SCS2.First == ICK_Array_To_Pointer)
1809 FromType2 = Context.getArrayDecayedType(FromType2);
1810
1811 // Canonicalize all of the types.
1812 FromType1 = Context.getCanonicalType(FromType1);
1813 ToType1 = Context.getCanonicalType(ToType1);
1814 FromType2 = Context.getCanonicalType(FromType2);
1815 ToType2 = Context.getCanonicalType(ToType2);
1816
Douglas Gregor0e343382008-10-29 14:50:44 +00001817 // C++ [over.ics.rank]p4b3:
Douglas Gregor14046502008-10-23 00:40:37 +00001818 //
1819 // If class B is derived directly or indirectly from class A and
1820 // class C is derived directly or indirectly from B,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001821 //
1822 // For Objective-C, we let A, B, and C also be Objective-C
1823 // interfaces.
Douglas Gregor0e343382008-10-29 14:50:44 +00001824
1825 // Compare based on pointer conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001826 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor3f5a00c2008-11-27 01:19:21 +00001827 SCS2.Second == ICK_Pointer_Conversion &&
1828 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1829 FromType1->isPointerType() && FromType2->isPointerType() &&
1830 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregor14046502008-10-23 00:40:37 +00001831 QualType FromPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001832 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001833 QualType ToPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001834 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001835 QualType FromPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001836 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001837 QualType ToPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001838 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor24a90a52008-11-26 23:31:11 +00001839
1840 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1841 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1842 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1843 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1844
Douglas Gregor0e343382008-10-29 14:50:44 +00001845 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor14046502008-10-23 00:40:37 +00001846 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1847 if (IsDerivedFrom(ToPointee1, ToPointee2))
1848 return ImplicitConversionSequence::Better;
1849 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1850 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001851
1852 if (ToIface1 && ToIface2) {
1853 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1854 return ImplicitConversionSequence::Better;
1855 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1856 return ImplicitConversionSequence::Worse;
1857 }
Douglas Gregor14046502008-10-23 00:40:37 +00001858 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001859
1860 // -- conversion of B* to A* is better than conversion of C* to A*,
1861 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1862 if (IsDerivedFrom(FromPointee2, FromPointee1))
1863 return ImplicitConversionSequence::Better;
1864 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1865 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001866
1867 if (FromIface1 && FromIface2) {
1868 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1869 return ImplicitConversionSequence::Better;
1870 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1871 return ImplicitConversionSequence::Worse;
1872 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001873 }
Douglas Gregor14046502008-10-23 00:40:37 +00001874 }
1875
Douglas Gregor0e343382008-10-29 14:50:44 +00001876 // Compare based on reference bindings.
1877 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1878 SCS1.Second == ICK_Derived_To_Base) {
1879 // -- binding of an expression of type C to a reference of type
1880 // B& is better than binding an expression of type C to a
1881 // reference of type A&,
1882 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1883 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1884 if (IsDerivedFrom(ToType1, ToType2))
1885 return ImplicitConversionSequence::Better;
1886 else if (IsDerivedFrom(ToType2, ToType1))
1887 return ImplicitConversionSequence::Worse;
1888 }
1889
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001890 // -- binding of an expression of type B to a reference of type
1891 // A& is better than binding an expression of type C to a
1892 // reference of type A&,
Douglas Gregor0e343382008-10-29 14:50:44 +00001893 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1894 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1895 if (IsDerivedFrom(FromType2, FromType1))
1896 return ImplicitConversionSequence::Better;
1897 else if (IsDerivedFrom(FromType1, FromType2))
1898 return ImplicitConversionSequence::Worse;
1899 }
1900 }
1901
1902
1903 // FIXME: conversion of A::* to B::* is better than conversion of
1904 // A::* to C::*,
1905
1906 // FIXME: conversion of B::* to C::* is better than conversion of
1907 // A::* to C::*, and
1908
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001909 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1910 SCS1.Second == ICK_Derived_To_Base) {
1911 // -- conversion of C to B is better than conversion of C to A,
1912 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1913 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1914 if (IsDerivedFrom(ToType1, ToType2))
1915 return ImplicitConversionSequence::Better;
1916 else if (IsDerivedFrom(ToType2, ToType1))
1917 return ImplicitConversionSequence::Worse;
1918 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001919
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001920 // -- conversion of B to A is better than conversion of C to A.
1921 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1922 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1923 if (IsDerivedFrom(FromType2, FromType1))
1924 return ImplicitConversionSequence::Better;
1925 else if (IsDerivedFrom(FromType1, FromType2))
1926 return ImplicitConversionSequence::Worse;
1927 }
1928 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001929
Douglas Gregor14046502008-10-23 00:40:37 +00001930 return ImplicitConversionSequence::Indistinguishable;
1931}
1932
Douglas Gregor81c29152008-10-29 00:13:59 +00001933/// TryCopyInitialization - Try to copy-initialize a value of type
1934/// ToType from the expression From. Return the implicit conversion
1935/// sequence required to pass this argument, which may be a bad
1936/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001937/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redla55834a2009-04-12 17:16:29 +00001938/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1939/// then we treat @p From as an rvalue, even if it is an lvalue.
Douglas Gregor81c29152008-10-29 00:13:59 +00001940ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001941Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlssone0f3ee62009-08-27 17:37:39 +00001942 bool SuppressUserConversions, bool ForceRValue,
1943 bool InOverloadResolution) {
Douglas Gregorfcb19192009-02-11 23:02:49 +00001944 if (ToType->isReferenceType()) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001945 ImplicitConversionSequence ICS;
Anders Carlsson8f809f92009-08-27 17:30:43 +00001946 CheckReferenceInit(From, ToType,
1947 SuppressUserConversions,
1948 /*AllowExplicit=*/false,
1949 ForceRValue,
1950 &ICS);
Douglas Gregor81c29152008-10-29 00:13:59 +00001951 return ICS;
1952 } else {
Anders Carlsson6ed4a612009-08-27 17:24:15 +00001953 return TryImplicitConversion(From, ToType,
1954 SuppressUserConversions,
1955 /*AllowExplicit=*/false,
Anders Carlsson8e4c1692009-08-28 15:33:32 +00001956 ForceRValue,
1957 InOverloadResolution);
Douglas Gregor81c29152008-10-29 00:13:59 +00001958 }
1959}
1960
Sebastian Redla55834a2009-04-12 17:16:29 +00001961/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1962/// the expression @p From. Returns true (and emits a diagnostic) if there was
1963/// an error, returns false if the initialization succeeded. Elidable should
1964/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1965/// differently in C++0x for this case.
Douglas Gregor81c29152008-10-29 00:13:59 +00001966bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001967 const char* Flavor, bool Elidable) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001968 if (!getLangOptions().CPlusPlus) {
1969 // In C, argument passing is the same as performing an assignment.
1970 QualType FromType = From->getType();
Douglas Gregor144b06c2009-04-29 22:16:16 +00001971
Douglas Gregor81c29152008-10-29 00:13:59 +00001972 AssignConvertType ConvTy =
1973 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor144b06c2009-04-29 22:16:16 +00001974 if (ConvTy != Compatible &&
1975 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1976 ConvTy = Compatible;
1977
Douglas Gregor81c29152008-10-29 00:13:59 +00001978 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1979 FromType, From, Flavor);
Douglas Gregor81c29152008-10-29 00:13:59 +00001980 }
Sebastian Redla55834a2009-04-12 17:16:29 +00001981
Chris Lattner271d4c22008-11-24 05:29:24 +00001982 if (ToType->isReferenceType())
Anders Carlsson8f809f92009-08-27 17:30:43 +00001983 return CheckReferenceInit(From, ToType,
1984 /*SuppressUserConversions=*/false,
1985 /*AllowExplicit=*/false,
1986 /*ForceRValue=*/false);
Chris Lattner271d4c22008-11-24 05:29:24 +00001987
Sebastian Redla55834a2009-04-12 17:16:29 +00001988 if (!PerformImplicitConversion(From, ToType, Flavor,
1989 /*AllowExplicit=*/false, Elidable))
Chris Lattner271d4c22008-11-24 05:29:24 +00001990 return false;
Sebastian Redla55834a2009-04-12 17:16:29 +00001991
Chris Lattner271d4c22008-11-24 05:29:24 +00001992 return Diag(From->getSourceRange().getBegin(),
1993 diag::err_typecheck_convert_incompatible)
1994 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001995}
1996
Douglas Gregor5ed15042008-11-18 23:14:02 +00001997/// TryObjectArgumentInitialization - Try to initialize the object
1998/// parameter of the given member function (@c Method) from the
1999/// expression @p From.
2000ImplicitConversionSequence
2001Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
2002 QualType ClassType = Context.getTypeDeclType(Method->getParent());
2003 unsigned MethodQuals = Method->getTypeQualifiers();
2004 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
2005
2006 // Set up the conversion sequence as a "bad" conversion, to allow us
2007 // to exit early.
2008 ImplicitConversionSequence ICS;
2009 ICS.Standard.setAsIdentityConversion();
2010 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2011
2012 // We need to have an object of class type.
2013 QualType FromType = From->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002014 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002015 FromType = PT->getPointeeType();
2016
2017 assert(FromType->isRecordType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00002018
2019 // The implicit object parmeter is has the type "reference to cv X",
2020 // where X is the class of which the function is a member
2021 // (C++ [over.match.funcs]p4). However, when finding an implicit
2022 // conversion sequence for the argument, we are not allowed to
2023 // create temporaries or perform user-defined conversions
2024 // (C++ [over.match.funcs]p5). We perform a simplified version of
2025 // reference binding here, that allows class rvalues to bind to
2026 // non-constant references.
2027
2028 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2029 // with the implicit object parameter (C++ [over.match.funcs]p5).
2030 QualType FromTypeCanon = Context.getCanonicalType(FromType);
2031 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2032 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2033 return ICS;
2034
2035 // Check that we have either the same type or a derived type. It
2036 // affects the conversion rank.
2037 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2038 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2039 ICS.Standard.Second = ICK_Identity;
2040 else if (IsDerivedFrom(FromType, ClassType))
2041 ICS.Standard.Second = ICK_Derived_To_Base;
2042 else
2043 return ICS;
2044
2045 // Success. Mark this as a reference binding.
2046 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2047 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2048 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2049 ICS.Standard.ReferenceBinding = true;
2050 ICS.Standard.DirectBinding = true;
Sebastian Redl9bc16ad2009-03-29 22:46:24 +00002051 ICS.Standard.RRefBinding = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002052 return ICS;
2053}
2054
2055/// PerformObjectArgumentInitialization - Perform initialization of
2056/// the implicit object parameter for the given Method with the given
2057/// expression.
2058bool
2059Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002060 QualType FromRecordType, DestType;
2061 QualType ImplicitParamRecordType =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002062 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002063
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002064 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002065 FromRecordType = PT->getPointeeType();
2066 DestType = Method->getThisType(Context);
2067 } else {
2068 FromRecordType = From->getType();
2069 DestType = ImplicitParamRecordType;
2070 }
2071
Douglas Gregor5ed15042008-11-18 23:14:02 +00002072 ImplicitConversionSequence ICS
2073 = TryObjectArgumentInitialization(From, Method);
2074 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2075 return Diag(From->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002076 diag::err_implicit_object_parameter_init)
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002077 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2078
Douglas Gregor5ed15042008-11-18 23:14:02 +00002079 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002080 CheckDerivedToBaseConversion(FromRecordType,
2081 ImplicitParamRecordType,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002082 From->getSourceRange().getBegin(),
2083 From->getSourceRange()))
2084 return true;
2085
Anders Carlssone25b6cd2009-08-07 18:45:49 +00002086 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
2087 /*isLvalue=*/true);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002088 return false;
2089}
2090
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002091/// TryContextuallyConvertToBool - Attempt to contextually convert the
2092/// expression From to bool (C++0x [conv]p3).
2093ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Anders Carlsson6ed4a612009-08-27 17:24:15 +00002094 return TryImplicitConversion(From, Context.BoolTy,
2095 // FIXME: Are these flags correct?
2096 /*SuppressUserConversions=*/false,
2097 /*AllowExplicit=*/true,
Anders Carlsson8e4c1692009-08-28 15:33:32 +00002098 /*ForceRValue=*/false,
2099 /*InOverloadResolution=*/false);
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002100}
2101
2102/// PerformContextuallyConvertToBool - Perform a contextual conversion
2103/// of the expression From to bool (C++0x [conv]p3).
2104bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2105 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2106 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2107 return false;
2108
2109 return Diag(From->getSourceRange().getBegin(),
2110 diag::err_typecheck_bool_condition)
2111 << From->getType() << From->getSourceRange();
2112}
2113
Douglas Gregord2baafd2008-10-21 16:13:35 +00002114/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002115/// candidate functions, using the given function call arguments. If
2116/// @p SuppressUserConversions, then don't allow user-defined
2117/// conversions via constructors or conversion operators.
Sebastian Redla55834a2009-04-12 17:16:29 +00002118/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2119/// hacky way to implement the overloading rules for elidable copy
2120/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregord2baafd2008-10-21 16:13:35 +00002121void
2122Sema::AddOverloadCandidate(FunctionDecl *Function,
2123 Expr **Args, unsigned NumArgs,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002124 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002125 bool SuppressUserConversions,
2126 bool ForceRValue)
Douglas Gregord2baafd2008-10-21 16:13:35 +00002127{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002128 const FunctionProtoType* Proto
2129 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregord2baafd2008-10-21 16:13:35 +00002130 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregor60714f92008-11-07 22:36:19 +00002131 assert(!isa<CXXConversionDecl>(Function) &&
2132 "Use AddConversionCandidate for conversion functions");
Douglas Gregorb60eb752009-06-25 22:08:12 +00002133 assert(!Function->getDescribedFunctionTemplate() &&
2134 "Use AddTemplateOverloadCandidate for function templates");
2135
Douglas Gregor3257fb52008-12-22 05:46:06 +00002136 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00002137 if (!isa<CXXConstructorDecl>(Method)) {
2138 // If we get here, it's because we're calling a member function
2139 // that is named without a member access expression (e.g.,
2140 // "this->f") that was either written explicitly or created
2141 // implicitly. This can happen with a qualified call to a member
2142 // function, e.g., X::f(). We use a NULL object as the implied
2143 // object argument (C++ [over.call.func]p3).
2144 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2145 SuppressUserConversions, ForceRValue);
2146 return;
2147 }
2148 // We treat a constructor like a non-member function, since its object
2149 // argument doesn't participate in overload resolution.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002150 }
2151
2152
Douglas Gregord2baafd2008-10-21 16:13:35 +00002153 // Add this candidate
2154 CandidateSet.push_back(OverloadCandidate());
2155 OverloadCandidate& Candidate = CandidateSet.back();
2156 Candidate.Function = Function;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002157 Candidate.Viable = true;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002158 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002159 Candidate.IgnoreObjectArgument = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00002160
2161 unsigned NumArgsInProto = Proto->getNumArgs();
2162
2163 // (C++ 13.3.2p2): A candidate function having fewer than m
2164 // parameters is viable only if it has an ellipsis in its parameter
2165 // list (8.3.5).
2166 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2167 Candidate.Viable = false;
2168 return;
2169 }
2170
2171 // (C++ 13.3.2p2): A candidate function having more than m parameters
2172 // is viable only if the (m+1)st parameter has a default argument
2173 // (8.3.6). For the purposes of overload resolution, the
2174 // parameter list is truncated on the right, so that there are
2175 // exactly m parameters.
2176 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2177 if (NumArgs < MinRequiredArgs) {
2178 // Not enough arguments.
2179 Candidate.Viable = false;
2180 return;
2181 }
2182
2183 // Determine the implicit conversion sequences for each of the
2184 // arguments.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002185 Candidate.Conversions.resize(NumArgs);
2186 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2187 if (ArgIdx < NumArgsInProto) {
2188 // (C++ 13.3.2p3): for F to be a viable function, there shall
2189 // exist for each argument an implicit conversion sequence
2190 // (13.3.3.1) that converts that argument to the corresponding
2191 // parameter of F.
2192 QualType ParamType = Proto->getArgType(ArgIdx);
2193 Candidate.Conversions[ArgIdx]
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002194 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlssone0f3ee62009-08-27 17:37:39 +00002195 SuppressUserConversions, ForceRValue,
2196 /*InOverloadResolution=*/true);
Douglas Gregord2baafd2008-10-21 16:13:35 +00002197 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002198 == ImplicitConversionSequence::BadConversion) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00002199 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002200 break;
2201 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002202 } else {
2203 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2204 // argument for which there is no corresponding parameter is
2205 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2206 Candidate.Conversions[ArgIdx].ConversionKind
2207 = ImplicitConversionSequence::EllipsisConversion;
2208 }
2209 }
2210}
2211
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002212/// \brief Add all of the function declarations in the given function set to
2213/// the overload canddiate set.
2214void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2215 Expr **Args, unsigned NumArgs,
2216 OverloadCandidateSet& CandidateSet,
2217 bool SuppressUserConversions) {
2218 for (FunctionSet::const_iterator F = Functions.begin(),
2219 FEnd = Functions.end();
Douglas Gregor993a0602009-06-27 21:05:07 +00002220 F != FEnd; ++F) {
2221 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
2222 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2223 SuppressUserConversions);
2224 else
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002225 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2226 /*FIXME: explicit args */false, 0, 0,
2227 Args, NumArgs, CandidateSet,
Douglas Gregor993a0602009-06-27 21:05:07 +00002228 SuppressUserConversions);
2229 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002230}
2231
Douglas Gregor5ed15042008-11-18 23:14:02 +00002232/// AddMethodCandidate - Adds the given C++ member function to the set
2233/// of candidate functions, using the given function call arguments
2234/// and the object argument (@c Object). For example, in a call
2235/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2236/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2237/// allow user-defined conversions via constructors or conversion
Sebastian Redla55834a2009-04-12 17:16:29 +00002238/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2239/// a slightly hacky way to implement the overloading rules for elidable copy
2240/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor5ed15042008-11-18 23:14:02 +00002241void
2242Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2243 Expr **Args, unsigned NumArgs,
2244 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002245 bool SuppressUserConversions, bool ForceRValue)
Douglas Gregor5ed15042008-11-18 23:14:02 +00002246{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002247 const FunctionProtoType* Proto
2248 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00002249 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redlbd261962009-04-16 17:51:27 +00002250 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor5ed15042008-11-18 23:14:02 +00002251 "Use AddConversionCandidate for conversion functions");
Sebastian Redlbd261962009-04-16 17:51:27 +00002252 assert(!isa<CXXConstructorDecl>(Method) &&
2253 "Use AddOverloadCandidate for constructors");
Douglas Gregor5ed15042008-11-18 23:14:02 +00002254
2255 // Add this candidate
2256 CandidateSet.push_back(OverloadCandidate());
2257 OverloadCandidate& Candidate = CandidateSet.back();
2258 Candidate.Function = Method;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002259 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002260 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002261
2262 unsigned NumArgsInProto = Proto->getNumArgs();
2263
2264 // (C++ 13.3.2p2): A candidate function having fewer than m
2265 // parameters is viable only if it has an ellipsis in its parameter
2266 // list (8.3.5).
2267 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2268 Candidate.Viable = false;
2269 return;
2270 }
2271
2272 // (C++ 13.3.2p2): A candidate function having more than m parameters
2273 // is viable only if the (m+1)st parameter has a default argument
2274 // (8.3.6). For the purposes of overload resolution, the
2275 // parameter list is truncated on the right, so that there are
2276 // exactly m parameters.
2277 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2278 if (NumArgs < MinRequiredArgs) {
2279 // Not enough arguments.
2280 Candidate.Viable = false;
2281 return;
2282 }
2283
2284 Candidate.Viable = true;
2285 Candidate.Conversions.resize(NumArgs + 1);
2286
Douglas Gregor3257fb52008-12-22 05:46:06 +00002287 if (Method->isStatic() || !Object)
2288 // The implicit object argument is ignored.
2289 Candidate.IgnoreObjectArgument = true;
2290 else {
2291 // Determine the implicit conversion sequence for the object
2292 // parameter.
2293 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2294 if (Candidate.Conversions[0].ConversionKind
2295 == ImplicitConversionSequence::BadConversion) {
2296 Candidate.Viable = false;
2297 return;
2298 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002299 }
2300
2301 // Determine the implicit conversion sequences for each of the
2302 // arguments.
2303 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2304 if (ArgIdx < NumArgsInProto) {
2305 // (C++ 13.3.2p3): for F to be a viable function, there shall
2306 // exist for each argument an implicit conversion sequence
2307 // (13.3.3.1) that converts that argument to the corresponding
2308 // parameter of F.
2309 QualType ParamType = Proto->getArgType(ArgIdx);
2310 Candidate.Conversions[ArgIdx + 1]
2311 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlssone0f3ee62009-08-27 17:37:39 +00002312 SuppressUserConversions, ForceRValue,
Anders Carlsson8e4c1692009-08-28 15:33:32 +00002313 /*InOverloadResolution=*/true);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002314 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2315 == ImplicitConversionSequence::BadConversion) {
2316 Candidate.Viable = false;
2317 break;
2318 }
2319 } else {
2320 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2321 // argument for which there is no corresponding parameter is
2322 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2323 Candidate.Conversions[ArgIdx + 1].ConversionKind
2324 = ImplicitConversionSequence::EllipsisConversion;
2325 }
2326 }
2327}
2328
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002329/// \brief Add a C++ member function template as a candidate to the candidate
2330/// set, using template argument deduction to produce an appropriate member
2331/// function template specialization.
2332void
2333Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2334 bool HasExplicitTemplateArgs,
2335 const TemplateArgument *ExplicitTemplateArgs,
2336 unsigned NumExplicitTemplateArgs,
2337 Expr *Object, Expr **Args, unsigned NumArgs,
2338 OverloadCandidateSet& CandidateSet,
2339 bool SuppressUserConversions,
2340 bool ForceRValue) {
2341 // C++ [over.match.funcs]p7:
2342 // In each case where a candidate is a function template, candidate
2343 // function template specializations are generated using template argument
2344 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2345 // candidate functions in the usual way.113) A given name can refer to one
2346 // or more function templates and also to a set of overloaded non-template
2347 // functions. In such a case, the candidate functions generated from each
2348 // function template are combined with the set of non-template candidate
2349 // functions.
2350 TemplateDeductionInfo Info(Context);
2351 FunctionDecl *Specialization = 0;
2352 if (TemplateDeductionResult Result
2353 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2354 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2355 Args, NumArgs, Specialization, Info)) {
2356 // FIXME: Record what happened with template argument deduction, so
2357 // that we can give the user a beautiful diagnostic.
2358 (void)Result;
2359 return;
2360 }
2361
2362 // Add the function template specialization produced by template argument
2363 // deduction as a candidate.
2364 assert(Specialization && "Missing member function template specialization?");
2365 assert(isa<CXXMethodDecl>(Specialization) &&
2366 "Specialization is not a member function?");
2367 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
2368 CandidateSet, SuppressUserConversions, ForceRValue);
2369}
2370
Douglas Gregor8c860df2009-08-21 23:19:43 +00002371/// \brief Add a C++ function template specialization as a candidate
2372/// in the candidate set, using template argument deduction to produce
2373/// an appropriate function template specialization.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002374void
2375Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002376 bool HasExplicitTemplateArgs,
2377 const TemplateArgument *ExplicitTemplateArgs,
2378 unsigned NumExplicitTemplateArgs,
Douglas Gregorb60eb752009-06-25 22:08:12 +00002379 Expr **Args, unsigned NumArgs,
2380 OverloadCandidateSet& CandidateSet,
2381 bool SuppressUserConversions,
2382 bool ForceRValue) {
2383 // C++ [over.match.funcs]p7:
2384 // In each case where a candidate is a function template, candidate
2385 // function template specializations are generated using template argument
2386 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2387 // candidate functions in the usual way.113) A given name can refer to one
2388 // or more function templates and also to a set of overloaded non-template
2389 // functions. In such a case, the candidate functions generated from each
2390 // function template are combined with the set of non-template candidate
2391 // functions.
2392 TemplateDeductionInfo Info(Context);
2393 FunctionDecl *Specialization = 0;
2394 if (TemplateDeductionResult Result
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002395 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2396 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2397 Args, NumArgs, Specialization, Info)) {
Douglas Gregorb60eb752009-06-25 22:08:12 +00002398 // FIXME: Record what happened with template argument deduction, so
2399 // that we can give the user a beautiful diagnostic.
2400 (void)Result;
2401 return;
2402 }
2403
2404 // Add the function template specialization produced by template argument
2405 // deduction as a candidate.
2406 assert(Specialization && "Missing function template specialization?");
2407 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2408 SuppressUserConversions, ForceRValue);
2409}
2410
Douglas Gregor60714f92008-11-07 22:36:19 +00002411/// AddConversionCandidate - Add a C++ conversion function as a
2412/// candidate in the candidate set (C++ [over.match.conv],
2413/// C++ [over.match.copy]). From is the expression we're converting from,
2414/// and ToType is the type that we're eventually trying to convert to
2415/// (which may or may not be the same type as the type that the
2416/// conversion function produces).
2417void
2418Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2419 Expr *From, QualType ToType,
2420 OverloadCandidateSet& CandidateSet) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00002421 assert(!Conversion->getDescribedFunctionTemplate() &&
2422 "Conversion function templates use AddTemplateConversionCandidate");
2423
Douglas Gregor60714f92008-11-07 22:36:19 +00002424 // Add this candidate
2425 CandidateSet.push_back(OverloadCandidate());
2426 OverloadCandidate& Candidate = CandidateSet.back();
2427 Candidate.Function = Conversion;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002428 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002429 Candidate.IgnoreObjectArgument = false;
Douglas Gregor60714f92008-11-07 22:36:19 +00002430 Candidate.FinalConversion.setAsIdentityConversion();
2431 Candidate.FinalConversion.FromTypePtr
2432 = Conversion->getConversionType().getAsOpaquePtr();
2433 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2434
Douglas Gregor5ed15042008-11-18 23:14:02 +00002435 // Determine the implicit conversion sequence for the implicit
2436 // object parameter.
Douglas Gregor60714f92008-11-07 22:36:19 +00002437 Candidate.Viable = true;
2438 Candidate.Conversions.resize(1);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002439 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregor60714f92008-11-07 22:36:19 +00002440
Douglas Gregor60714f92008-11-07 22:36:19 +00002441 if (Candidate.Conversions[0].ConversionKind
2442 == ImplicitConversionSequence::BadConversion) {
2443 Candidate.Viable = false;
2444 return;
2445 }
2446
2447 // To determine what the conversion from the result of calling the
2448 // conversion function to the type we're eventually trying to
2449 // convert to (ToType), we need to synthesize a call to the
2450 // conversion function and attempt copy initialization from it. This
2451 // makes sure that we get the right semantics with respect to
2452 // lvalues/rvalues and the type. Fortunately, we can allocate this
2453 // call on the stack and we don't need its arguments to be
2454 // well-formed.
2455 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2456 SourceLocation());
2457 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002458 CastExpr::CK_Unknown,
Douglas Gregor70d26122008-11-12 17:17:38 +00002459 &ConversionRef, false);
Ted Kremenek362abcd2009-02-09 20:51:47 +00002460
2461 // Note that it is safe to allocate CallExpr on the stack here because
2462 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2463 // allocator).
2464 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor60714f92008-11-07 22:36:19 +00002465 Conversion->getConversionType().getNonReferenceType(),
2466 SourceLocation());
Anders Carlsson06386552009-08-27 17:18:13 +00002467 ImplicitConversionSequence ICS =
2468 TryCopyInitialization(&Call, ToType,
2469 /*SuppressUserConversions=*/true,
Anders Carlssone0f3ee62009-08-27 17:37:39 +00002470 /*ForceRValue=*/false,
2471 /*InOverloadResolution=*/false);
Anders Carlsson06386552009-08-27 17:18:13 +00002472
Douglas Gregor60714f92008-11-07 22:36:19 +00002473 switch (ICS.ConversionKind) {
2474 case ImplicitConversionSequence::StandardConversion:
2475 Candidate.FinalConversion = ICS.Standard;
2476 break;
2477
2478 case ImplicitConversionSequence::BadConversion:
2479 Candidate.Viable = false;
2480 break;
2481
2482 default:
2483 assert(false &&
2484 "Can only end up with a standard conversion sequence or failure");
2485 }
2486}
2487
Douglas Gregor8c860df2009-08-21 23:19:43 +00002488/// \brief Adds a conversion function template specialization
2489/// candidate to the overload set, using template argument deduction
2490/// to deduce the template arguments of the conversion function
2491/// template from the type that we are converting to (C++
2492/// [temp.deduct.conv]).
2493void
2494Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2495 Expr *From, QualType ToType,
2496 OverloadCandidateSet &CandidateSet) {
2497 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2498 "Only conversion function templates permitted here");
2499
2500 TemplateDeductionInfo Info(Context);
2501 CXXConversionDecl *Specialization = 0;
2502 if (TemplateDeductionResult Result
2503 = DeduceTemplateArguments(FunctionTemplate, ToType,
2504 Specialization, Info)) {
2505 // FIXME: Record what happened with template argument deduction, so
2506 // that we can give the user a beautiful diagnostic.
2507 (void)Result;
2508 return;
2509 }
2510
2511 // Add the conversion function template specialization produced by
2512 // template argument deduction as a candidate.
2513 assert(Specialization && "Missing function template specialization?");
2514 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2515}
2516
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002517/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2518/// converts the given @c Object to a function pointer via the
2519/// conversion function @c Conversion, and then attempts to call it
2520/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2521/// the type of function that we'll eventually be calling.
2522void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002523 const FunctionProtoType *Proto,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002524 Expr *Object, Expr **Args, unsigned NumArgs,
2525 OverloadCandidateSet& CandidateSet) {
2526 CandidateSet.push_back(OverloadCandidate());
2527 OverloadCandidate& Candidate = CandidateSet.back();
2528 Candidate.Function = 0;
2529 Candidate.Surrogate = Conversion;
2530 Candidate.Viable = true;
2531 Candidate.IsSurrogate = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002532 Candidate.IgnoreObjectArgument = false;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002533 Candidate.Conversions.resize(NumArgs + 1);
2534
2535 // Determine the implicit conversion sequence for the implicit
2536 // object parameter.
2537 ImplicitConversionSequence ObjectInit
2538 = TryObjectArgumentInitialization(Object, Conversion);
2539 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2540 Candidate.Viable = false;
2541 return;
2542 }
2543
2544 // The first conversion is actually a user-defined conversion whose
2545 // first conversion is ObjectInit's standard conversion (which is
2546 // effectively a reference binding). Record it as such.
2547 Candidate.Conversions[0].ConversionKind
2548 = ImplicitConversionSequence::UserDefinedConversion;
2549 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2550 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2551 Candidate.Conversions[0].UserDefined.After
2552 = Candidate.Conversions[0].UserDefined.Before;
2553 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2554
2555 // Find the
2556 unsigned NumArgsInProto = Proto->getNumArgs();
2557
2558 // (C++ 13.3.2p2): A candidate function having fewer than m
2559 // parameters is viable only if it has an ellipsis in its parameter
2560 // list (8.3.5).
2561 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2562 Candidate.Viable = false;
2563 return;
2564 }
2565
2566 // Function types don't have any default arguments, so just check if
2567 // we have enough arguments.
2568 if (NumArgs < NumArgsInProto) {
2569 // Not enough arguments.
2570 Candidate.Viable = false;
2571 return;
2572 }
2573
2574 // Determine the implicit conversion sequences for each of the
2575 // arguments.
2576 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2577 if (ArgIdx < NumArgsInProto) {
2578 // (C++ 13.3.2p3): for F to be a viable function, there shall
2579 // exist for each argument an implicit conversion sequence
2580 // (13.3.3.1) that converts that argument to the corresponding
2581 // parameter of F.
2582 QualType ParamType = Proto->getArgType(ArgIdx);
2583 Candidate.Conversions[ArgIdx + 1]
2584 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson06386552009-08-27 17:18:13 +00002585 /*SuppressUserConversions=*/false,
Anders Carlssone0f3ee62009-08-27 17:37:39 +00002586 /*ForceRValue=*/false,
2587 /*InOverloadResolution=*/false);
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002588 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2589 == ImplicitConversionSequence::BadConversion) {
2590 Candidate.Viable = false;
2591 break;
2592 }
2593 } else {
2594 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2595 // argument for which there is no corresponding parameter is
2596 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2597 Candidate.Conversions[ArgIdx + 1].ConversionKind
2598 = ImplicitConversionSequence::EllipsisConversion;
2599 }
2600 }
2601}
2602
Mike Stumpe127ae32009-05-16 07:39:55 +00002603// FIXME: This will eventually be removed, once we've migrated all of the
2604// operator overloading logic over to the scheme used by binary operators, which
2605// works for template instantiation.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002606void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor48a87322009-02-04 16:44:47 +00002607 SourceLocation OpLoc,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002608 Expr **Args, unsigned NumArgs,
Douglas Gregor48a87322009-02-04 16:44:47 +00002609 OverloadCandidateSet& CandidateSet,
2610 SourceRange OpRange) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002611
2612 FunctionSet Functions;
2613
2614 QualType T1 = Args[0]->getType();
2615 QualType T2;
2616 if (NumArgs > 1)
2617 T2 = Args[1]->getType();
2618
2619 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregorde72f3e2009-05-19 00:01:19 +00002620 if (S)
2621 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002622 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2623 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2624 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2625 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2626}
2627
2628/// \brief Add overload candidates for overloaded operators that are
2629/// member functions.
2630///
2631/// Add the overloaded operator candidates that are member functions
2632/// for the operator Op that was used in an operator expression such
2633/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2634/// CandidateSet will store the added overload candidates. (C++
2635/// [over.match.oper]).
2636void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2637 SourceLocation OpLoc,
2638 Expr **Args, unsigned NumArgs,
2639 OverloadCandidateSet& CandidateSet,
2640 SourceRange OpRange) {
Douglas Gregor5ed15042008-11-18 23:14:02 +00002641 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2642
2643 // C++ [over.match.oper]p3:
2644 // For a unary operator @ with an operand of a type whose
2645 // cv-unqualified version is T1, and for a binary operator @ with
2646 // a left operand of a type whose cv-unqualified version is T1 and
2647 // a right operand of a type whose cv-unqualified version is T2,
2648 // three sets of candidate functions, designated member
2649 // candidates, non-member candidates and built-in candidates, are
2650 // constructed as follows:
2651 QualType T1 = Args[0]->getType();
2652 QualType T2;
2653 if (NumArgs > 1)
2654 T2 = Args[1]->getType();
2655
2656 // -- If T1 is a class type, the set of member candidates is the
2657 // result of the qualified lookup of T1::operator@
2658 // (13.3.1.1.1); otherwise, the set of member candidates is
2659 // empty.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002660 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor2993edd2009-08-27 23:35:55 +00002661 // Complete the type if it can be completed. Otherwise, we're done.
2662 if (RequireCompleteType(OpLoc, T1, PartialDiagnostic(0)))
2663 return;
2664
2665 LookupResult Operators = LookupQualifiedName(T1Rec->getDecl(), OpName,
2666 LookupOrdinaryName, false);
2667 for (LookupResult::iterator Oper = Operators.begin(),
2668 OperEnd = Operators.end();
2669 Oper != OperEnd;
2670 ++Oper)
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002671 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2672 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002673 /*SuppressUserConversions=*/false);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002674 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002675}
2676
Douglas Gregor70d26122008-11-12 17:17:38 +00002677/// AddBuiltinCandidate - Add a candidate for a built-in
2678/// operator. ResultTy and ParamTys are the result and parameter types
2679/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorab141112009-01-13 00:52:54 +00002680/// arguments being passed to the candidate. IsAssignmentOperator
2681/// should be true when this built-in candidate is an assignment
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002682/// operator. NumContextualBoolArguments is the number of arguments
2683/// (at the beginning of the argument list) that will be contextually
2684/// converted to bool.
Douglas Gregor70d26122008-11-12 17:17:38 +00002685void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2686 Expr **Args, unsigned NumArgs,
Douglas Gregorab141112009-01-13 00:52:54 +00002687 OverloadCandidateSet& CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002688 bool IsAssignmentOperator,
2689 unsigned NumContextualBoolArguments) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002690 // Add this candidate
2691 CandidateSet.push_back(OverloadCandidate());
2692 OverloadCandidate& Candidate = CandidateSet.back();
2693 Candidate.Function = 0;
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00002694 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002695 Candidate.IgnoreObjectArgument = false;
Douglas Gregor70d26122008-11-12 17:17:38 +00002696 Candidate.BuiltinTypes.ResultTy = ResultTy;
2697 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2698 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2699
2700 // Determine the implicit conversion sequences for each of the
2701 // arguments.
2702 Candidate.Viable = true;
2703 Candidate.Conversions.resize(NumArgs);
2704 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorab141112009-01-13 00:52:54 +00002705 // C++ [over.match.oper]p4:
2706 // For the built-in assignment operators, conversions of the
2707 // left operand are restricted as follows:
2708 // -- no temporaries are introduced to hold the left operand, and
2709 // -- no user-defined conversions are applied to the left
2710 // operand to achieve a type match with the left-most
2711 // parameter of a built-in candidate.
2712 //
2713 // We block these conversions by turning off user-defined
2714 // conversions, since that is the only way that initialization of
2715 // a reference to a non-class type can occur from something that
2716 // is not of the same type.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002717 if (ArgIdx < NumContextualBoolArguments) {
2718 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2719 "Contextual conversion to bool requires bool type");
2720 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2721 } else {
2722 Candidate.Conversions[ArgIdx]
2723 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson06386552009-08-27 17:18:13 +00002724 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlssone0f3ee62009-08-27 17:37:39 +00002725 /*ForceRValue=*/false,
2726 /*InOverloadResolution=*/false);
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002727 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002728 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002729 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002730 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002731 break;
2732 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002733 }
2734}
2735
2736/// BuiltinCandidateTypeSet - A set of types that will be used for the
2737/// candidate operator functions for built-in operators (C++
2738/// [over.built]). The types are separated into pointer types and
2739/// enumeration types.
2740class BuiltinCandidateTypeSet {
2741 /// TypeSet - A set of types.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002742 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregor70d26122008-11-12 17:17:38 +00002743
2744 /// PointerTypes - The set of pointer types that will be used in the
2745 /// built-in candidates.
2746 TypeSet PointerTypes;
2747
Sebastian Redl674d1b72009-04-19 21:53:20 +00002748 /// MemberPointerTypes - The set of member pointer types that will be
2749 /// used in the built-in candidates.
2750 TypeSet MemberPointerTypes;
2751
Douglas Gregor70d26122008-11-12 17:17:38 +00002752 /// EnumerationTypes - The set of enumeration types that will be
2753 /// used in the built-in candidates.
2754 TypeSet EnumerationTypes;
2755
Douglas Gregorb35c7992009-08-24 15:23:48 +00002756 /// Sema - The semantic analysis instance where we are building the
2757 /// candidate type set.
2758 Sema &SemaRef;
2759
Douglas Gregor70d26122008-11-12 17:17:38 +00002760 /// Context - The AST context in which we will build the type sets.
2761 ASTContext &Context;
2762
Sebastian Redl674d1b72009-04-19 21:53:20 +00002763 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2764 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002765
2766public:
2767 /// iterator - Iterates through the types that are part of the set.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002768 typedef TypeSet::iterator iterator;
Douglas Gregor70d26122008-11-12 17:17:38 +00002769
Douglas Gregorb35c7992009-08-24 15:23:48 +00002770 BuiltinCandidateTypeSet(Sema &SemaRef)
2771 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregor70d26122008-11-12 17:17:38 +00002772
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002773 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2774 bool AllowExplicitConversions);
Douglas Gregor70d26122008-11-12 17:17:38 +00002775
2776 /// pointer_begin - First pointer type found;
2777 iterator pointer_begin() { return PointerTypes.begin(); }
2778
Sebastian Redl674d1b72009-04-19 21:53:20 +00002779 /// pointer_end - Past the last pointer type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002780 iterator pointer_end() { return PointerTypes.end(); }
2781
Sebastian Redl674d1b72009-04-19 21:53:20 +00002782 /// member_pointer_begin - First member pointer type found;
2783 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2784
2785 /// member_pointer_end - Past the last member pointer type found;
2786 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2787
Douglas Gregor70d26122008-11-12 17:17:38 +00002788 /// enumeration_begin - First enumeration type found;
2789 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2790
Sebastian Redl674d1b72009-04-19 21:53:20 +00002791 /// enumeration_end - Past the last enumeration type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002792 iterator enumeration_end() { return EnumerationTypes.end(); }
2793};
2794
Sebastian Redl674d1b72009-04-19 21:53:20 +00002795/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregor70d26122008-11-12 17:17:38 +00002796/// the set of pointer types along with any more-qualified variants of
2797/// that type. For example, if @p Ty is "int const *", this routine
2798/// will add "int const *", "int const volatile *", "int const
2799/// restrict *", and "int const volatile restrict *" to the set of
2800/// pointer types. Returns true if the add of @p Ty itself succeeded,
2801/// false otherwise.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002802bool
2803BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002804 // Insert this type.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002805 if (!PointerTypes.insert(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002806 return false;
2807
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002808 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002809 QualType PointeeTy = PointerTy->getPointeeType();
2810 // FIXME: Optimize this so that we don't keep trying to add the same types.
2811
Mike Stumpe127ae32009-05-16 07:39:55 +00002812 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2813 // pointer conversions that don't cast away constness?
Douglas Gregor70d26122008-11-12 17:17:38 +00002814 if (!PointeeTy.isConstQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002815 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002816 (Context.getPointerType(PointeeTy.withConst()));
2817 if (!PointeeTy.isVolatileQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002818 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002819 (Context.getPointerType(PointeeTy.withVolatile()));
2820 if (!PointeeTy.isRestrictQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002821 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002822 (Context.getPointerType(PointeeTy.withRestrict()));
2823 }
2824
2825 return true;
2826}
2827
Sebastian Redl674d1b72009-04-19 21:53:20 +00002828/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2829/// to the set of pointer types along with any more-qualified variants of
2830/// that type. For example, if @p Ty is "int const *", this routine
2831/// will add "int const *", "int const volatile *", "int const
2832/// restrict *", and "int const volatile restrict *" to the set of
2833/// pointer types. Returns true if the add of @p Ty itself succeeded,
2834/// false otherwise.
2835bool
2836BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2837 QualType Ty) {
2838 // Insert this type.
2839 if (!MemberPointerTypes.insert(Ty))
2840 return false;
2841
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002842 if (const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>()) {
Sebastian Redl674d1b72009-04-19 21:53:20 +00002843 QualType PointeeTy = PointerTy->getPointeeType();
2844 const Type *ClassTy = PointerTy->getClass();
2845 // FIXME: Optimize this so that we don't keep trying to add the same types.
2846
2847 if (!PointeeTy.isConstQualified())
2848 AddMemberPointerWithMoreQualifiedTypeVariants
2849 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2850 if (!PointeeTy.isVolatileQualified())
2851 AddMemberPointerWithMoreQualifiedTypeVariants
2852 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2853 if (!PointeeTy.isRestrictQualified())
2854 AddMemberPointerWithMoreQualifiedTypeVariants
2855 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2856 }
2857
2858 return true;
2859}
2860
Douglas Gregor70d26122008-11-12 17:17:38 +00002861/// AddTypesConvertedFrom - Add each of the types to which the type @p
2862/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl674d1b72009-04-19 21:53:20 +00002863/// primarily interested in pointer types and enumeration types. We also
2864/// take member pointer types, for the conditional operator.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002865/// AllowUserConversions is true if we should look at the conversion
2866/// functions of a class type, and AllowExplicitConversions if we
2867/// should also include the explicit conversion functions of a class
2868/// type.
2869void
2870BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2871 bool AllowUserConversions,
2872 bool AllowExplicitConversions) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002873 // Only deal with canonical types.
2874 Ty = Context.getCanonicalType(Ty);
2875
2876 // Look through reference types; they aren't part of the type of an
2877 // expression for the purposes of conversions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002878 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregor70d26122008-11-12 17:17:38 +00002879 Ty = RefTy->getPointeeType();
2880
2881 // We don't care about qualifiers on the type.
2882 Ty = Ty.getUnqualifiedType();
2883
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002884 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002885 QualType PointeeTy = PointerTy->getPointeeType();
2886
2887 // Insert our type, and its more-qualified variants, into the set
2888 // of types.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002889 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002890 return;
2891
2892 // Add 'cv void*' to our set of types.
2893 if (!Ty->isVoidType()) {
2894 QualType QualVoid
2895 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl674d1b72009-04-19 21:53:20 +00002896 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregor70d26122008-11-12 17:17:38 +00002897 }
2898
2899 // If this is a pointer to a class type, add pointers to its bases
2900 // (with the same level of cv-qualification as the original
2901 // derived class, of course).
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002902 if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002903 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2904 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2905 Base != ClassDecl->bases_end(); ++Base) {
2906 QualType BaseTy = Context.getCanonicalType(Base->getType());
2907 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2908
2909 // Add the pointer type, recursively, so that we get all of
2910 // the indirect base classes, too.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002911 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002912 }
2913 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00002914 } else if (Ty->isMemberPointerType()) {
2915 // Member pointers are far easier, since the pointee can't be converted.
2916 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2917 return;
Douglas Gregor70d26122008-11-12 17:17:38 +00002918 } else if (Ty->isEnumeralType()) {
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002919 EnumerationTypes.insert(Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002920 } else if (AllowUserConversions) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002921 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorb35c7992009-08-24 15:23:48 +00002922 if (SemaRef.RequireCompleteType(SourceLocation(), Ty, 0)) {
2923 // No conversion functions in incomplete types.
2924 return;
2925 }
2926
Douglas Gregor70d26122008-11-12 17:17:38 +00002927 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2928 // FIXME: Visit conversion functions in the base classes, too.
2929 OverloadedFunctionDecl *Conversions
2930 = ClassDecl->getConversionFunctions();
2931 for (OverloadedFunctionDecl::function_iterator Func
2932 = Conversions->function_begin();
2933 Func != Conversions->function_end(); ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00002934 CXXConversionDecl *Conv;
2935 FunctionTemplateDecl *ConvTemplate;
2936 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
2937
2938 // Skip conversion function templates; they don't tell us anything
2939 // about which builtin types we can convert to.
2940 if (ConvTemplate)
2941 continue;
2942
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002943 if (AllowExplicitConversions || !Conv->isExplicit())
2944 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002945 }
2946 }
2947 }
2948}
2949
Douglas Gregor9a375942009-08-24 13:43:27 +00002950/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
2951/// the volatile- and non-volatile-qualified assignment operators for the
2952/// given type to the candidate set.
2953static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
2954 QualType T,
2955 Expr **Args,
2956 unsigned NumArgs,
2957 OverloadCandidateSet &CandidateSet) {
2958 QualType ParamTypes[2];
2959
2960 // T& operator=(T&, T)
2961 ParamTypes[0] = S.Context.getLValueReferenceType(T);
2962 ParamTypes[1] = T;
2963 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2964 /*IsAssignmentOperator=*/true);
2965
2966 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
2967 // volatile T& operator=(volatile T&, T)
2968 ParamTypes[0] = S.Context.getLValueReferenceType(T.withVolatile());
2969 ParamTypes[1] = T;
2970 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2971 /*IsAssignmentOperator=*/true);
2972 }
2973}
2974
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002975/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2976/// operator overloads to the candidate set (C++ [over.built]), based
2977/// on the operator @p Op and the arguments given. For example, if the
2978/// operator is a binary '+', this routine might add "int
2979/// operator+(int, int)" to cover integer addition.
Douglas Gregor70d26122008-11-12 17:17:38 +00002980void
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002981Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2982 Expr **Args, unsigned NumArgs,
2983 OverloadCandidateSet& CandidateSet) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002984 // The set of "promoted arithmetic types", which are the arithmetic
2985 // types are that preserved by promotion (C++ [over.built]p2). Note
2986 // that the first few of these types are the promoted integral
2987 // types; these types need to be first.
2988 // FIXME: What about complex?
2989 const unsigned FirstIntegralType = 0;
2990 const unsigned LastIntegralType = 13;
2991 const unsigned FirstPromotedIntegralType = 7,
2992 LastPromotedIntegralType = 13;
2993 const unsigned FirstPromotedArithmeticType = 7,
2994 LastPromotedArithmeticType = 16;
2995 const unsigned NumArithmeticTypes = 16;
2996 QualType ArithmeticTypes[NumArithmeticTypes] = {
Alisdair Meredith2bcacb62009-07-14 06:30:34 +00002997 Context.BoolTy, Context.CharTy, Context.WCharTy,
Douglas Gregor9a375942009-08-24 13:43:27 +00002998// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregor70d26122008-11-12 17:17:38 +00002999 Context.SignedCharTy, Context.ShortTy,
3000 Context.UnsignedCharTy, Context.UnsignedShortTy,
3001 Context.IntTy, Context.LongTy, Context.LongLongTy,
3002 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3003 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3004 };
3005
3006 // Find all of the types that the arguments can convert to, but only
3007 // if the operator we're looking at has built-in operator candidates
3008 // that make use of these types.
Douglas Gregorb35c7992009-08-24 15:23:48 +00003009 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregor70d26122008-11-12 17:17:38 +00003010 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3011 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003012 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregor70d26122008-11-12 17:17:38 +00003013 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003014 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redlbd261962009-04-16 17:51:27 +00003015 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003016 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003017 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3018 true,
3019 (Op == OO_Exclaim ||
3020 Op == OO_AmpAmp ||
3021 Op == OO_PipePipe));
Douglas Gregor70d26122008-11-12 17:17:38 +00003022 }
3023
3024 bool isComparison = false;
3025 switch (Op) {
3026 case OO_None:
3027 case NUM_OVERLOADED_OPERATORS:
3028 assert(false && "Expected an overloaded operator");
3029 break;
3030
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003031 case OO_Star: // '*' is either unary or binary
3032 if (NumArgs == 1)
3033 goto UnaryStar;
3034 else
3035 goto BinaryStar;
3036 break;
3037
3038 case OO_Plus: // '+' is either unary or binary
3039 if (NumArgs == 1)
3040 goto UnaryPlus;
3041 else
3042 goto BinaryPlus;
3043 break;
3044
3045 case OO_Minus: // '-' is either unary or binary
3046 if (NumArgs == 1)
3047 goto UnaryMinus;
3048 else
3049 goto BinaryMinus;
3050 break;
3051
3052 case OO_Amp: // '&' is either unary or binary
3053 if (NumArgs == 1)
3054 goto UnaryAmp;
3055 else
3056 goto BinaryAmp;
3057
3058 case OO_PlusPlus:
3059 case OO_MinusMinus:
3060 // C++ [over.built]p3:
3061 //
3062 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3063 // is either volatile or empty, there exist candidate operator
3064 // functions of the form
3065 //
3066 // VQ T& operator++(VQ T&);
3067 // T operator++(VQ T&, int);
3068 //
3069 // C++ [over.built]p4:
3070 //
3071 // For every pair (T, VQ), where T is an arithmetic type other
3072 // than bool, and VQ is either volatile or empty, there exist
3073 // candidate operator functions of the form
3074 //
3075 // VQ T& operator--(VQ T&);
3076 // T operator--(VQ T&, int);
3077 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
3078 Arith < NumArithmeticTypes; ++Arith) {
3079 QualType ArithTy = ArithmeticTypes[Arith];
3080 QualType ParamTypes[2]
Sebastian Redlce6fff02009-03-16 23:22:08 +00003081 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003082
3083 // Non-volatile version.
3084 if (NumArgs == 1)
3085 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3086 else
3087 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3088
3089 // Volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003090 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003091 if (NumArgs == 1)
3092 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3093 else
3094 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3095 }
3096
3097 // C++ [over.built]p5:
3098 //
3099 // For every pair (T, VQ), where T is a cv-qualified or
3100 // cv-unqualified object type, and VQ is either volatile or
3101 // empty, there exist candidate operator functions of the form
3102 //
3103 // T*VQ& operator++(T*VQ&);
3104 // T*VQ& operator--(T*VQ&);
3105 // T* operator++(T*VQ&, int);
3106 // T* operator--(T*VQ&, int);
3107 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3108 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3109 // Skip pointer types that aren't pointers to object types.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003110 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003111 continue;
3112
3113 QualType ParamTypes[2] = {
Sebastian Redlce6fff02009-03-16 23:22:08 +00003114 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003115 };
3116
3117 // Without volatile
3118 if (NumArgs == 1)
3119 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3120 else
3121 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3122
3123 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3124 // With volatile
Sebastian Redlce6fff02009-03-16 23:22:08 +00003125 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003126 if (NumArgs == 1)
3127 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3128 else
3129 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3130 }
3131 }
3132 break;
3133
3134 UnaryStar:
3135 // C++ [over.built]p6:
3136 // For every cv-qualified or cv-unqualified object type T, there
3137 // exist candidate operator functions of the form
3138 //
3139 // T& operator*(T*);
3140 //
3141 // C++ [over.built]p7:
3142 // For every function type T, there exist candidate operator
3143 // functions of the form
3144 // T& operator*(T*);
3145 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3146 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3147 QualType ParamTy = *Ptr;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003148 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003149 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003150 &ParamTy, Args, 1, CandidateSet);
3151 }
3152 break;
3153
3154 UnaryPlus:
3155 // C++ [over.built]p8:
3156 // For every type T, there exist candidate operator functions of
3157 // the form
3158 //
3159 // T* operator+(T*);
3160 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3161 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3162 QualType ParamTy = *Ptr;
3163 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3164 }
3165
3166 // Fall through
3167
3168 UnaryMinus:
3169 // C++ [over.built]p9:
3170 // For every promoted arithmetic type T, there exist candidate
3171 // operator functions of the form
3172 //
3173 // T operator+(T);
3174 // T operator-(T);
3175 for (unsigned Arith = FirstPromotedArithmeticType;
3176 Arith < LastPromotedArithmeticType; ++Arith) {
3177 QualType ArithTy = ArithmeticTypes[Arith];
3178 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3179 }
3180 break;
3181
3182 case OO_Tilde:
3183 // C++ [over.built]p10:
3184 // For every promoted integral type T, there exist candidate
3185 // operator functions of the form
3186 //
3187 // T operator~(T);
3188 for (unsigned Int = FirstPromotedIntegralType;
3189 Int < LastPromotedIntegralType; ++Int) {
3190 QualType IntTy = ArithmeticTypes[Int];
3191 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3192 }
3193 break;
3194
Douglas Gregor70d26122008-11-12 17:17:38 +00003195 case OO_New:
3196 case OO_Delete:
3197 case OO_Array_New:
3198 case OO_Array_Delete:
Douglas Gregor70d26122008-11-12 17:17:38 +00003199 case OO_Call:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003200 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregor70d26122008-11-12 17:17:38 +00003201 break;
3202
3203 case OO_Comma:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003204 UnaryAmp:
3205 case OO_Arrow:
Douglas Gregor70d26122008-11-12 17:17:38 +00003206 // C++ [over.match.oper]p3:
3207 // -- For the operator ',', the unary operator '&', or the
3208 // operator '->', the built-in candidates set is empty.
Douglas Gregor70d26122008-11-12 17:17:38 +00003209 break;
3210
Douglas Gregor9a375942009-08-24 13:43:27 +00003211 case OO_EqualEqual:
3212 case OO_ExclaimEqual:
3213 // C++ [over.match.oper]p16:
3214 // For every pointer to member type T, there exist candidate operator
3215 // functions of the form
3216 //
3217 // bool operator==(T,T);
3218 // bool operator!=(T,T);
3219 for (BuiltinCandidateTypeSet::iterator
3220 MemPtr = CandidateTypes.member_pointer_begin(),
3221 MemPtrEnd = CandidateTypes.member_pointer_end();
3222 MemPtr != MemPtrEnd;
3223 ++MemPtr) {
3224 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3225 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3226 }
3227
3228 // Fall through
3229
Douglas Gregor70d26122008-11-12 17:17:38 +00003230 case OO_Less:
3231 case OO_Greater:
3232 case OO_LessEqual:
3233 case OO_GreaterEqual:
Douglas Gregor70d26122008-11-12 17:17:38 +00003234 // C++ [over.built]p15:
3235 //
3236 // For every pointer or enumeration type T, there exist
3237 // candidate operator functions of the form
3238 //
3239 // bool operator<(T, T);
3240 // bool operator>(T, T);
3241 // bool operator<=(T, T);
3242 // bool operator>=(T, T);
3243 // bool operator==(T, T);
3244 // bool operator!=(T, T);
3245 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3246 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3247 QualType ParamTypes[2] = { *Ptr, *Ptr };
3248 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3249 }
3250 for (BuiltinCandidateTypeSet::iterator Enum
3251 = CandidateTypes.enumeration_begin();
3252 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3253 QualType ParamTypes[2] = { *Enum, *Enum };
3254 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3255 }
3256
3257 // Fall through.
3258 isComparison = true;
3259
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003260 BinaryPlus:
3261 BinaryMinus:
Douglas Gregor70d26122008-11-12 17:17:38 +00003262 if (!isComparison) {
3263 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3264
3265 // C++ [over.built]p13:
3266 //
3267 // For every cv-qualified or cv-unqualified object type T
3268 // there exist candidate operator functions of the form
3269 //
3270 // T* operator+(T*, ptrdiff_t);
3271 // T& operator[](T*, ptrdiff_t); [BELOW]
3272 // T* operator-(T*, ptrdiff_t);
3273 // T* operator+(ptrdiff_t, T*);
3274 // T& operator[](ptrdiff_t, T*); [BELOW]
3275 //
3276 // C++ [over.built]p14:
3277 //
3278 // For every T, where T is a pointer to object type, there
3279 // exist candidate operator functions of the form
3280 //
3281 // ptrdiff_t operator-(T, T);
3282 for (BuiltinCandidateTypeSet::iterator Ptr
3283 = CandidateTypes.pointer_begin();
3284 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3285 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3286
3287 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3288 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3289
3290 if (Op == OO_Plus) {
3291 // T* operator+(ptrdiff_t, T*);
3292 ParamTypes[0] = ParamTypes[1];
3293 ParamTypes[1] = *Ptr;
3294 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3295 } else {
3296 // ptrdiff_t operator-(T, T);
3297 ParamTypes[1] = *Ptr;
3298 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3299 Args, 2, CandidateSet);
3300 }
3301 }
3302 }
3303 // Fall through
3304
Douglas Gregor70d26122008-11-12 17:17:38 +00003305 case OO_Slash:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003306 BinaryStar:
Sebastian Redlbd261962009-04-16 17:51:27 +00003307 Conditional:
Douglas Gregor70d26122008-11-12 17:17:38 +00003308 // C++ [over.built]p12:
3309 //
3310 // For every pair of promoted arithmetic types L and R, there
3311 // exist candidate operator functions of the form
3312 //
3313 // LR operator*(L, R);
3314 // LR operator/(L, R);
3315 // LR operator+(L, R);
3316 // LR operator-(L, R);
3317 // bool operator<(L, R);
3318 // bool operator>(L, R);
3319 // bool operator<=(L, R);
3320 // bool operator>=(L, R);
3321 // bool operator==(L, R);
3322 // bool operator!=(L, R);
3323 //
3324 // where LR is the result of the usual arithmetic conversions
3325 // between types L and R.
Sebastian Redlbd261962009-04-16 17:51:27 +00003326 //
3327 // C++ [over.built]p24:
3328 //
3329 // For every pair of promoted arithmetic types L and R, there exist
3330 // candidate operator functions of the form
3331 //
3332 // LR operator?(bool, L, R);
3333 //
3334 // where LR is the result of the usual arithmetic conversions
3335 // between types L and R.
3336 // Our candidates ignore the first parameter.
Douglas Gregor70d26122008-11-12 17:17:38 +00003337 for (unsigned Left = FirstPromotedArithmeticType;
3338 Left < LastPromotedArithmeticType; ++Left) {
3339 for (unsigned Right = FirstPromotedArithmeticType;
3340 Right < LastPromotedArithmeticType; ++Right) {
3341 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman6ae7d112009-08-19 07:44:53 +00003342 QualType Result
3343 = isComparison
3344 ? Context.BoolTy
3345 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003346 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3347 }
3348 }
3349 break;
3350
3351 case OO_Percent:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003352 BinaryAmp:
Douglas Gregor70d26122008-11-12 17:17:38 +00003353 case OO_Caret:
3354 case OO_Pipe:
3355 case OO_LessLess:
3356 case OO_GreaterGreater:
3357 // C++ [over.built]p17:
3358 //
3359 // For every pair of promoted integral types L and R, there
3360 // exist candidate operator functions of the form
3361 //
3362 // LR operator%(L, R);
3363 // LR operator&(L, R);
3364 // LR operator^(L, R);
3365 // LR operator|(L, R);
3366 // L operator<<(L, R);
3367 // L operator>>(L, R);
3368 //
3369 // where LR is the result of the usual arithmetic conversions
3370 // between types L and R.
3371 for (unsigned Left = FirstPromotedIntegralType;
3372 Left < LastPromotedIntegralType; ++Left) {
3373 for (unsigned Right = FirstPromotedIntegralType;
3374 Right < LastPromotedIntegralType; ++Right) {
3375 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3376 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3377 ? LandR[0]
Eli Friedman6ae7d112009-08-19 07:44:53 +00003378 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003379 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3380 }
3381 }
3382 break;
3383
3384 case OO_Equal:
3385 // C++ [over.built]p20:
3386 //
3387 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor9a375942009-08-24 13:43:27 +00003388 // pointer to member type and VQ is either volatile or
Douglas Gregor70d26122008-11-12 17:17:38 +00003389 // empty, there exist candidate operator functions of the form
3390 //
3391 // VQ T& operator=(VQ T&, T);
Douglas Gregor9a375942009-08-24 13:43:27 +00003392 for (BuiltinCandidateTypeSet::iterator
3393 Enum = CandidateTypes.enumeration_begin(),
3394 EnumEnd = CandidateTypes.enumeration_end();
3395 Enum != EnumEnd; ++Enum)
3396 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
3397 CandidateSet);
3398 for (BuiltinCandidateTypeSet::iterator
3399 MemPtr = CandidateTypes.member_pointer_begin(),
3400 MemPtrEnd = CandidateTypes.member_pointer_end();
3401 MemPtr != MemPtrEnd; ++MemPtr)
3402 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
3403 CandidateSet);
3404 // Fall through.
Douglas Gregor70d26122008-11-12 17:17:38 +00003405
3406 case OO_PlusEqual:
3407 case OO_MinusEqual:
3408 // C++ [over.built]p19:
3409 //
3410 // For every pair (T, VQ), where T is any type and VQ is either
3411 // volatile or empty, there exist candidate operator functions
3412 // of the form
3413 //
3414 // T*VQ& operator=(T*VQ&, T*);
3415 //
3416 // C++ [over.built]p21:
3417 //
3418 // For every pair (T, VQ), where T is a cv-qualified or
3419 // cv-unqualified object type and VQ is either volatile or
3420 // empty, there exist candidate operator functions of the form
3421 //
3422 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3423 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3424 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3425 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3426 QualType ParamTypes[2];
3427 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3428
3429 // non-volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003430 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorab141112009-01-13 00:52:54 +00003431 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3432 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003433
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003434 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3435 // volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003436 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregorab141112009-01-13 00:52:54 +00003437 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3438 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003439 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003440 }
3441 // Fall through.
3442
3443 case OO_StarEqual:
3444 case OO_SlashEqual:
3445 // C++ [over.built]p18:
3446 //
3447 // For every triple (L, VQ, R), where L is an arithmetic type,
3448 // VQ is either volatile or empty, and R is a promoted
3449 // arithmetic type, there exist candidate operator functions of
3450 // the form
3451 //
3452 // VQ L& operator=(VQ L&, R);
3453 // VQ L& operator*=(VQ L&, R);
3454 // VQ L& operator/=(VQ L&, R);
3455 // VQ L& operator+=(VQ L&, R);
3456 // VQ L& operator-=(VQ L&, R);
3457 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3458 for (unsigned Right = FirstPromotedArithmeticType;
3459 Right < LastPromotedArithmeticType; ++Right) {
3460 QualType ParamTypes[2];
3461 ParamTypes[1] = ArithmeticTypes[Right];
3462
3463 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003464 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorab141112009-01-13 00:52:54 +00003465 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3466 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003467
3468 // Add this built-in operator as a candidate (VQ is 'volatile').
3469 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003470 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorab141112009-01-13 00:52:54 +00003471 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3472 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003473 }
3474 }
3475 break;
3476
3477 case OO_PercentEqual:
3478 case OO_LessLessEqual:
3479 case OO_GreaterGreaterEqual:
3480 case OO_AmpEqual:
3481 case OO_CaretEqual:
3482 case OO_PipeEqual:
3483 // C++ [over.built]p22:
3484 //
3485 // For every triple (L, VQ, R), where L is an integral type, VQ
3486 // is either volatile or empty, and R is a promoted integral
3487 // type, there exist candidate operator functions of the form
3488 //
3489 // VQ L& operator%=(VQ L&, R);
3490 // VQ L& operator<<=(VQ L&, R);
3491 // VQ L& operator>>=(VQ L&, R);
3492 // VQ L& operator&=(VQ L&, R);
3493 // VQ L& operator^=(VQ L&, R);
3494 // VQ L& operator|=(VQ L&, R);
3495 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3496 for (unsigned Right = FirstPromotedIntegralType;
3497 Right < LastPromotedIntegralType; ++Right) {
3498 QualType ParamTypes[2];
3499 ParamTypes[1] = ArithmeticTypes[Right];
3500
3501 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003502 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003503 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3504
3505 // Add this built-in operator as a candidate (VQ is 'volatile').
3506 ParamTypes[0] = ArithmeticTypes[Left];
3507 ParamTypes[0].addVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003508 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003509 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3510 }
3511 }
3512 break;
3513
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003514 case OO_Exclaim: {
3515 // C++ [over.operator]p23:
3516 //
3517 // There also exist candidate operator functions of the form
3518 //
3519 // bool operator!(bool);
3520 // bool operator&&(bool, bool); [BELOW]
3521 // bool operator||(bool, bool); [BELOW]
3522 QualType ParamTy = Context.BoolTy;
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003523 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3524 /*IsAssignmentOperator=*/false,
3525 /*NumContextualBoolArguments=*/1);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003526 break;
3527 }
3528
Douglas Gregor70d26122008-11-12 17:17:38 +00003529 case OO_AmpAmp:
3530 case OO_PipePipe: {
3531 // C++ [over.operator]p23:
3532 //
3533 // There also exist candidate operator functions of the form
3534 //
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003535 // bool operator!(bool); [ABOVE]
Douglas Gregor70d26122008-11-12 17:17:38 +00003536 // bool operator&&(bool, bool);
3537 // bool operator||(bool, bool);
3538 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003539 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3540 /*IsAssignmentOperator=*/false,
3541 /*NumContextualBoolArguments=*/2);
Douglas Gregor70d26122008-11-12 17:17:38 +00003542 break;
3543 }
3544
3545 case OO_Subscript:
3546 // C++ [over.built]p13:
3547 //
3548 // For every cv-qualified or cv-unqualified object type T there
3549 // exist candidate operator functions of the form
3550 //
3551 // T* operator+(T*, ptrdiff_t); [ABOVE]
3552 // T& operator[](T*, ptrdiff_t);
3553 // T* operator-(T*, ptrdiff_t); [ABOVE]
3554 // T* operator+(ptrdiff_t, T*); [ABOVE]
3555 // T& operator[](ptrdiff_t, T*);
3556 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3557 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3558 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003559 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003560 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregor70d26122008-11-12 17:17:38 +00003561
3562 // T& operator[](T*, ptrdiff_t)
3563 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3564
3565 // T& operator[](ptrdiff_t, T*);
3566 ParamTypes[0] = ParamTypes[1];
3567 ParamTypes[1] = *Ptr;
3568 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3569 }
3570 break;
3571
3572 case OO_ArrowStar:
3573 // FIXME: No support for pointer-to-members yet.
3574 break;
Sebastian Redlbd261962009-04-16 17:51:27 +00003575
3576 case OO_Conditional:
3577 // Note that we don't consider the first argument, since it has been
3578 // contextually converted to bool long ago. The candidates below are
3579 // therefore added as binary.
3580 //
3581 // C++ [over.built]p24:
3582 // For every type T, where T is a pointer or pointer-to-member type,
3583 // there exist candidate operator functions of the form
3584 //
3585 // T operator?(bool, T, T);
3586 //
Sebastian Redlbd261962009-04-16 17:51:27 +00003587 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3588 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3589 QualType ParamTypes[2] = { *Ptr, *Ptr };
3590 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3591 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00003592 for (BuiltinCandidateTypeSet::iterator Ptr =
3593 CandidateTypes.member_pointer_begin(),
3594 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3595 QualType ParamTypes[2] = { *Ptr, *Ptr };
3596 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3597 }
Sebastian Redlbd261962009-04-16 17:51:27 +00003598 goto Conditional;
Douglas Gregor70d26122008-11-12 17:17:38 +00003599 }
3600}
3601
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003602/// \brief Add function candidates found via argument-dependent lookup
3603/// to the set of overloading candidates.
3604///
3605/// This routine performs argument-dependent name lookup based on the
3606/// given function name (which may also be an operator name) and adds
3607/// all of the overload candidates found by ADL to the overload
3608/// candidate set (C++ [basic.lookup.argdep]).
3609void
3610Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3611 Expr **Args, unsigned NumArgs,
3612 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003613 FunctionSet Functions;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003614
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003615 // Record all of the function candidates that we've already
3616 // added to the overload set, so that we don't add those same
3617 // candidates a second time.
3618 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3619 CandEnd = CandidateSet.end();
3620 Cand != CandEnd; ++Cand)
Douglas Gregor993a0602009-06-27 21:05:07 +00003621 if (Cand->Function) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003622 Functions.insert(Cand->Function);
Douglas Gregor993a0602009-06-27 21:05:07 +00003623 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3624 Functions.insert(FunTmpl);
3625 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003626
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003627 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003628
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003629 // Erase all of the candidates we already knew about.
3630 // FIXME: This is suboptimal. Is there a better way?
3631 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3632 CandEnd = CandidateSet.end();
3633 Cand != CandEnd; ++Cand)
Douglas Gregor993a0602009-06-27 21:05:07 +00003634 if (Cand->Function) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003635 Functions.erase(Cand->Function);
Douglas Gregor993a0602009-06-27 21:05:07 +00003636 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3637 Functions.erase(FunTmpl);
3638 }
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003639
3640 // For each of the ADL candidates we found, add it to the overload
3641 // set.
3642 for (FunctionSet::iterator Func = Functions.begin(),
3643 FuncEnd = Functions.end();
Douglas Gregor993a0602009-06-27 21:05:07 +00003644 Func != FuncEnd; ++Func) {
3645 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
3646 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet);
3647 else
Douglas Gregorc9a03b72009-06-30 23:57:56 +00003648 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
3649 /*FIXME: explicit args */false, 0, 0,
3650 Args, NumArgs, CandidateSet);
Douglas Gregor993a0602009-06-27 21:05:07 +00003651 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003652}
3653
Douglas Gregord2baafd2008-10-21 16:13:35 +00003654/// isBetterOverloadCandidate - Determines whether the first overload
3655/// candidate is a better candidate than the second (C++ 13.3.3p1).
3656bool
3657Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3658 const OverloadCandidate& Cand2)
3659{
3660 // Define viable functions to be better candidates than non-viable
3661 // functions.
3662 if (!Cand2.Viable)
3663 return Cand1.Viable;
3664 else if (!Cand1.Viable)
3665 return false;
3666
Douglas Gregor3257fb52008-12-22 05:46:06 +00003667 // C++ [over.match.best]p1:
3668 //
3669 // -- if F is a static member function, ICS1(F) is defined such
3670 // that ICS1(F) is neither better nor worse than ICS1(G) for
3671 // any function G, and, symmetrically, ICS1(G) is neither
3672 // better nor worse than ICS1(F).
3673 unsigned StartArg = 0;
3674 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3675 StartArg = 1;
Douglas Gregord2baafd2008-10-21 16:13:35 +00003676
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003677 // C++ [over.match.best]p1:
3678 // A viable function F1 is defined to be a better function than another
3679 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
3680 // conversion sequence than ICSi(F2), and then...
Douglas Gregord2baafd2008-10-21 16:13:35 +00003681 unsigned NumArgs = Cand1.Conversions.size();
3682 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3683 bool HasBetterConversion = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00003684 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00003685 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3686 Cand2.Conversions[ArgIdx])) {
3687 case ImplicitConversionSequence::Better:
3688 // Cand1 has a better conversion sequence.
3689 HasBetterConversion = true;
3690 break;
3691
3692 case ImplicitConversionSequence::Worse:
3693 // Cand1 can't be better than Cand2.
3694 return false;
3695
3696 case ImplicitConversionSequence::Indistinguishable:
3697 // Do nothing.
3698 break;
3699 }
3700 }
3701
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003702 // -- for some argument j, ICSj(F1) is a better conversion sequence than
3703 // ICSj(F2), or, if not that,
Douglas Gregord2baafd2008-10-21 16:13:35 +00003704 if (HasBetterConversion)
3705 return true;
3706
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003707 // - F1 is a non-template function and F2 is a function template
3708 // specialization, or, if not that,
3709 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3710 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3711 return true;
3712
3713 // -- F1 and F2 are function template specializations, and the function
3714 // template for F1 is more specialized than the template for F2
3715 // according to the partial ordering rules described in 14.5.5.2, or,
3716 // if not that,
Douglas Gregorf8e51672009-08-02 23:46:29 +00003717 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3718 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor8c860df2009-08-21 23:19:43 +00003719 if (FunctionTemplateDecl *BetterTemplate
3720 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3721 Cand2.Function->getPrimaryTemplate(),
3722 true))
3723 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003724
Douglas Gregor60714f92008-11-07 22:36:19 +00003725 // -- the context is an initialization by user-defined conversion
3726 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3727 // from the return type of F1 to the destination type (i.e.,
3728 // the type of the entity being initialized) is a better
3729 // conversion sequence than the standard conversion sequence
3730 // from the return type of F2 to the destination type.
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003731 if (Cand1.Function && Cand2.Function &&
3732 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregor60714f92008-11-07 22:36:19 +00003733 isa<CXXConversionDecl>(Cand2.Function)) {
3734 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3735 Cand2.FinalConversion)) {
3736 case ImplicitConversionSequence::Better:
3737 // Cand1 has a better conversion sequence.
3738 return true;
3739
3740 case ImplicitConversionSequence::Worse:
3741 // Cand1 can't be better than Cand2.
3742 return false;
3743
3744 case ImplicitConversionSequence::Indistinguishable:
3745 // Do nothing
3746 break;
3747 }
3748 }
3749
Douglas Gregord2baafd2008-10-21 16:13:35 +00003750 return false;
3751}
3752
Douglas Gregor98189262009-06-19 23:52:42 +00003753/// \brief Computes the best viable function (C++ 13.3.3)
3754/// within an overload candidate set.
3755///
3756/// \param CandidateSet the set of candidate functions.
3757///
3758/// \param Loc the location of the function name (or operator symbol) for
3759/// which overload resolution occurs.
3760///
3761/// \param Best f overload resolution was successful or found a deleted
3762/// function, Best points to the candidate function found.
3763///
3764/// \returns The result of overload resolution.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003765Sema::OverloadingResult
3766Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregor98189262009-06-19 23:52:42 +00003767 SourceLocation Loc,
Douglas Gregord2baafd2008-10-21 16:13:35 +00003768 OverloadCandidateSet::iterator& Best)
3769{
3770 // Find the best viable function.
3771 Best = CandidateSet.end();
3772 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3773 Cand != CandidateSet.end(); ++Cand) {
3774 if (Cand->Viable) {
3775 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3776 Best = Cand;
3777 }
3778 }
3779
3780 // If we didn't find any viable functions, abort.
3781 if (Best == CandidateSet.end())
3782 return OR_No_Viable_Function;
3783
3784 // Make sure that this function is better than every other viable
3785 // function. If not, we have an ambiguity.
3786 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3787 Cand != CandidateSet.end(); ++Cand) {
3788 if (Cand->Viable &&
3789 Cand != Best &&
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003790 !isBetterOverloadCandidate(*Best, *Cand)) {
3791 Best = CandidateSet.end();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003792 return OR_Ambiguous;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003793 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003794 }
3795
3796 // Best is the best viable function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00003797 if (Best->Function &&
3798 (Best->Function->isDeleted() ||
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003799 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregoraa57e862009-02-18 21:56:37 +00003800 return OR_Deleted;
3801
Douglas Gregor98189262009-06-19 23:52:42 +00003802 // C++ [basic.def.odr]p2:
3803 // An overloaded function is used if it is selected by overload resolution
3804 // when referred to from a potentially-evaluated expression. [Note: this
3805 // covers calls to named functions (5.2.2), operator overloading
3806 // (clause 13), user-defined conversions (12.3.2), allocation function for
3807 // placement new (5.3.4), as well as non-default initialization (8.5).
3808 if (Best->Function)
3809 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregord2baafd2008-10-21 16:13:35 +00003810 return OR_Success;
3811}
3812
3813/// PrintOverloadCandidates - When overload resolution fails, prints
3814/// diagnostic messages containing the candidates in the candidate
3815/// set. If OnlyViable is true, only viable candidates will be printed.
3816void
3817Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3818 bool OnlyViable)
3819{
3820 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3821 LastCand = CandidateSet.end();
3822 for (; Cand != LastCand; ++Cand) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003823 if (Cand->Viable || !OnlyViable) {
3824 if (Cand->Function) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003825 if (Cand->Function->isDeleted() ||
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003826 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003827 // Deleted or "unavailable" function.
3828 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3829 << Cand->Function->isDeleted();
3830 } else {
3831 // Normal function
3832 // FIXME: Give a better reason!
3833 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3834 }
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003835 } else if (Cand->IsSurrogate) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003836 // Desugar the type of the surrogate down to a function type,
3837 // retaining as many typedefs as possible while still showing
3838 // the function type (and, therefore, its parameter types).
3839 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003840 bool isLValueReference = false;
3841 bool isRValueReference = false;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003842 bool isPointer = false;
Sebastian Redlce6fff02009-03-16 23:22:08 +00003843 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003844 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003845 FnType = FnTypeRef->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003846 isLValueReference = true;
3847 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003848 FnType->getAs<RValueReferenceType>()) {
Sebastian Redlce6fff02009-03-16 23:22:08 +00003849 FnType = FnTypeRef->getPointeeType();
3850 isRValueReference = true;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003851 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003852 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003853 FnType = FnTypePtr->getPointeeType();
3854 isPointer = true;
3855 }
3856 // Desugar down to a function type.
3857 FnType = QualType(FnType->getAsFunctionType(), 0);
3858 // Reconstruct the pointer/reference as appropriate.
3859 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redlce6fff02009-03-16 23:22:08 +00003860 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3861 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003862
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003863 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003864 << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003865 } else {
3866 // FIXME: We need to get the identifier in here
Mike Stumpe127ae32009-05-16 07:39:55 +00003867 // FIXME: Do we want the error message to point at the operator?
3868 // (built-ins won't have a location)
Douglas Gregor70d26122008-11-12 17:17:38 +00003869 QualType FnType
3870 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3871 Cand->BuiltinTypes.ParamTypes,
3872 Cand->Conversions.size(),
3873 false, 0);
3874
Chris Lattner4bfd2232008-11-24 06:25:27 +00003875 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003876 }
3877 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003878 }
3879}
3880
Douglas Gregor45014fd2008-11-10 20:40:00 +00003881/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3882/// an overloaded function (C++ [over.over]), where @p From is an
3883/// expression with overloaded function type and @p ToType is the type
3884/// we're trying to resolve to. For example:
3885///
3886/// @code
3887/// int f(double);
3888/// int f(int);
3889///
3890/// int (*pfd)(double) = f; // selects f(double)
3891/// @endcode
3892///
3893/// This routine returns the resulting FunctionDecl if it could be
3894/// resolved, and NULL otherwise. When @p Complain is true, this
3895/// routine will emit diagnostics if there is an error.
3896FunctionDecl *
Sebastian Redl7434fc32009-02-04 21:23:32 +00003897Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor45014fd2008-11-10 20:40:00 +00003898 bool Complain) {
3899 QualType FunctionType = ToType;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003900 bool IsMember = false;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003901 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003902 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003903 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003904 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl7434fc32009-02-04 21:23:32 +00003905 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003906 ToType->getAs<MemberPointerType>()) {
Sebastian Redl7434fc32009-02-04 21:23:32 +00003907 FunctionType = MemTypePtr->getPointeeType();
3908 IsMember = true;
3909 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003910
3911 // We only look at pointers or references to functions.
Douglas Gregor72bb4992009-07-09 17:16:51 +00003912 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor62f78762009-07-08 20:55:45 +00003913 if (!FunctionType->isFunctionType())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003914 return 0;
3915
3916 // Find the actual overloaded function declaration.
3917 OverloadedFunctionDecl *Ovl = 0;
3918
3919 // C++ [over.over]p1:
3920 // [...] [Note: any redundant set of parentheses surrounding the
3921 // overloaded function name is ignored (5.1). ]
3922 Expr *OvlExpr = From->IgnoreParens();
3923
3924 // C++ [over.over]p1:
3925 // [...] The overloaded function name can be preceded by the &
3926 // operator.
3927 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3928 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3929 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3930 }
3931
3932 // Try to dig out the overloaded function.
Douglas Gregor62f78762009-07-08 20:55:45 +00003933 FunctionTemplateDecl *FunctionTemplate = 0;
3934 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003935 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor62f78762009-07-08 20:55:45 +00003936 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
3937 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003938
Douglas Gregor62f78762009-07-08 20:55:45 +00003939 // If there's no overloaded function declaration or function template,
3940 // we're done.
3941 if (!Ovl && !FunctionTemplate)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003942 return 0;
3943
Douglas Gregor62f78762009-07-08 20:55:45 +00003944 OverloadIterator Fun;
3945 if (Ovl)
3946 Fun = Ovl;
3947 else
3948 Fun = FunctionTemplate;
3949
Douglas Gregor45014fd2008-11-10 20:40:00 +00003950 // Look through all of the overloaded functions, searching for one
3951 // whose type matches exactly.
Douglas Gregora142a052009-07-08 23:33:52 +00003952 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
3953
3954 bool FoundNonTemplateFunction = false;
Douglas Gregor62f78762009-07-08 20:55:45 +00003955 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003956 // C++ [over.over]p3:
3957 // Non-member functions and static member functions match
Sebastian Redl3a75abf2009-02-05 12:33:33 +00003958 // targets of type "pointer-to-function" or "reference-to-function."
3959 // Nonstatic member functions match targets of
Sebastian Redl7434fc32009-02-04 21:23:32 +00003960 // type "pointer-to-member-function."
3961 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor62f78762009-07-08 20:55:45 +00003962
3963 if (FunctionTemplateDecl *FunctionTemplate
3964 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Douglas Gregora142a052009-07-08 23:33:52 +00003965 if (CXXMethodDecl *Method
3966 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
3967 // Skip non-static function templates when converting to pointer, and
3968 // static when converting to member pointer.
3969 if (Method->isStatic() == IsMember)
3970 continue;
3971 } else if (IsMember)
3972 continue;
3973
3974 // C++ [over.over]p2:
3975 // If the name is a function template, template argument deduction is
3976 // done (14.8.2.2), and if the argument deduction succeeds, the
3977 // resulting template argument list is used to generate a single
3978 // function template specialization, which is added to the set of
3979 // overloaded functions considered.
Douglas Gregor62f78762009-07-08 20:55:45 +00003980 FunctionDecl *Specialization = 0;
3981 TemplateDeductionInfo Info(Context);
3982 if (TemplateDeductionResult Result
3983 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
3984 /*FIXME:*/0, /*FIXME:*/0,
3985 FunctionType, Specialization, Info)) {
3986 // FIXME: make a note of the failed deduction for diagnostics.
3987 (void)Result;
3988 } else {
3989 assert(FunctionType
3990 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregora142a052009-07-08 23:33:52 +00003991 Matches.insert(
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00003992 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor62f78762009-07-08 20:55:45 +00003993 }
3994 }
3995
Sebastian Redl7434fc32009-02-04 21:23:32 +00003996 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3997 // Skip non-static functions when converting to pointer, and static
3998 // when converting to member pointer.
3999 if (Method->isStatic() == IsMember)
Douglas Gregor45014fd2008-11-10 20:40:00 +00004000 continue;
Douglas Gregora142a052009-07-08 23:33:52 +00004001 } else if (IsMember)
Sebastian Redl7434fc32009-02-04 21:23:32 +00004002 continue;
Douglas Gregor45014fd2008-11-10 20:40:00 +00004003
Douglas Gregorb60eb752009-06-25 22:08:12 +00004004 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregora142a052009-07-08 23:33:52 +00004005 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00004006 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregora142a052009-07-08 23:33:52 +00004007 FoundNonTemplateFunction = true;
4008 }
Douglas Gregor62f78762009-07-08 20:55:45 +00004009 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00004010 }
4011
Douglas Gregora142a052009-07-08 23:33:52 +00004012 // If there were 0 or 1 matches, we're done.
4013 if (Matches.empty())
4014 return 0;
4015 else if (Matches.size() == 1)
4016 return *Matches.begin();
4017
4018 // C++ [over.over]p4:
4019 // If more than one function is selected, [...]
4020 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
Douglas Gregor8c860df2009-08-21 23:19:43 +00004021 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregora142a052009-07-08 23:33:52 +00004022 if (FoundNonTemplateFunction) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00004023 // [...] any function template specializations in the set are
4024 // eliminated if the set also contains a non-template function, [...]
4025 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
Douglas Gregora142a052009-07-08 23:33:52 +00004026 if ((*M)->getPrimaryTemplate() == 0)
4027 RemainingMatches.push_back(*M);
4028 } else {
Douglas Gregor8c860df2009-08-21 23:19:43 +00004029 // [...] and any given function template specialization F1 is
4030 // eliminated if the set contains a second function template
4031 // specialization whose function template is more specialized
4032 // than the function template of F1 according to the partial
4033 // ordering rules of 14.5.5.2.
4034
4035 // The algorithm specified above is quadratic. We instead use a
4036 // two-pass algorithm (similar to the one used to identify the
4037 // best viable function in an overload set) that identifies the
4038 // best function template (if it exists).
4039 MatchIter Best = Matches.begin();
4040 MatchIter M = Best, MEnd = Matches.end();
4041 // Find the most specialized function.
4042 for (++M; M != MEnd; ++M)
4043 if (getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4044 (*Best)->getPrimaryTemplate(),
4045 false)
4046 == (*M)->getPrimaryTemplate())
4047 Best = M;
4048
4049 // Determine whether this function template is more specialized
4050 // that all of the others.
4051 bool Ambiguous = false;
4052 for (M = Matches.begin(); M != MEnd; ++M) {
4053 if (M != Best &&
4054 getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4055 (*Best)->getPrimaryTemplate(),
4056 false)
4057 != (*Best)->getPrimaryTemplate()) {
4058 Ambiguous = true;
4059 break;
4060 }
4061 }
4062
4063 // If one function template was more specialized than all of the
4064 // others, return it.
4065 if (!Ambiguous)
4066 return *Best;
4067
4068 // We could not find a most-specialized function template, which
4069 // is equivalent to having a set of function templates with more
4070 // than one such template. So, we place all of the function
4071 // templates into the set of remaining matches and produce a
4072 // diagnostic below. FIXME: we could perform the quadratic
4073 // algorithm here, pruning the result set to limit the number of
4074 // candidates output later.
4075 RemainingMatches.append(Matches.begin(), Matches.end());
Douglas Gregora142a052009-07-08 23:33:52 +00004076 }
4077
4078 // [...] After such eliminations, if any, there shall remain exactly one
4079 // selected function.
4080 if (RemainingMatches.size() == 1)
4081 return RemainingMatches.front();
4082
4083 // FIXME: We should probably return the same thing that BestViableFunction
4084 // returns (even if we issue the diagnostics here).
4085 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4086 << RemainingMatches[0]->getDeclName();
4087 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4088 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregor45014fd2008-11-10 20:40:00 +00004089 return 0;
4090}
4091
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004092/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004093/// (which eventually refers to the declaration Func) and the call
4094/// arguments Args/NumArgs, attempt to resolve the function call down
4095/// to a specific function. If overload resolution succeeds, returns
4096/// the function declaration produced by overload
Douglas Gregorbf4f0582008-11-26 06:01:48 +00004097/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004098/// arguments and Fn, and returns NULL.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004099FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004100 DeclarationName UnqualifiedName,
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004101 bool HasExplicitTemplateArgs,
4102 const TemplateArgument *ExplicitTemplateArgs,
4103 unsigned NumExplicitTemplateArgs,
Douglas Gregorbf4f0582008-11-26 06:01:48 +00004104 SourceLocation LParenLoc,
4105 Expr **Args, unsigned NumArgs,
4106 SourceLocation *CommaLocs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004107 SourceLocation RParenLoc,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004108 bool &ArgumentDependentLookup) {
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004109 OverloadCandidateSet CandidateSet;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004110
4111 // Add the functions denoted by Callee to the set of candidate
4112 // functions. While we're doing so, track whether argument-dependent
4113 // lookup still applies, per:
4114 //
4115 // C++0x [basic.lookup.argdep]p3:
4116 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4117 // and let Y be the lookup set produced by argument dependent
4118 // lookup (defined as follows). If X contains
4119 //
4120 // -- a declaration of a class member, or
4121 //
4122 // -- a block-scope function declaration that is not a
4123 // using-declaration, or
4124 //
4125 // -- a declaration that is neither a function or a function
4126 // template
4127 //
4128 // then Y is empty.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004129 if (OverloadedFunctionDecl *Ovl
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004130 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
4131 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4132 FuncEnd = Ovl->function_end();
4133 Func != FuncEnd; ++Func) {
Douglas Gregorb60eb752009-06-25 22:08:12 +00004134 DeclContext *Ctx = 0;
4135 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Func)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004136 if (HasExplicitTemplateArgs)
4137 continue;
4138
Douglas Gregorb60eb752009-06-25 22:08:12 +00004139 AddOverloadCandidate(FunDecl, Args, NumArgs, CandidateSet);
4140 Ctx = FunDecl->getDeclContext();
4141 } else {
4142 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*Func);
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004143 AddTemplateOverloadCandidate(FunTmpl, HasExplicitTemplateArgs,
4144 ExplicitTemplateArgs,
4145 NumExplicitTemplateArgs,
4146 Args, NumArgs, CandidateSet);
Douglas Gregorb60eb752009-06-25 22:08:12 +00004147 Ctx = FunTmpl->getDeclContext();
4148 }
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004149
Douglas Gregorb60eb752009-06-25 22:08:12 +00004150
4151 if (Ctx->isRecord() || Ctx->isFunctionOrMethod())
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004152 ArgumentDependentLookup = false;
4153 }
4154 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004155 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004156 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
4157
4158 if (Func->getDeclContext()->isRecord() ||
4159 Func->getDeclContext()->isFunctionOrMethod())
4160 ArgumentDependentLookup = false;
Douglas Gregorb60eb752009-06-25 22:08:12 +00004161 } else if (FunctionTemplateDecl *FuncTemplate
4162 = dyn_cast_or_null<FunctionTemplateDecl>(Callee)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004163 AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4164 ExplicitTemplateArgs,
4165 NumExplicitTemplateArgs,
4166 Args, NumArgs, CandidateSet);
Douglas Gregorb60eb752009-06-25 22:08:12 +00004167
4168 if (FuncTemplate->getDeclContext()->isRecord())
4169 ArgumentDependentLookup = false;
4170 }
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004171
4172 if (Callee)
4173 UnqualifiedName = Callee->getDeclName();
4174
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004175 // FIXME: Pass explicit template arguments through for ADL
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004176 if (ArgumentDependentLookup)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004177 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004178 CandidateSet);
4179
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004180 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004181 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00004182 case OR_Success:
4183 return Best->Function;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004184
4185 case OR_No_Viable_Function:
Chris Lattner4a526112009-02-17 07:29:20 +00004186 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004187 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004188 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004189 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4190 break;
4191
4192 case OR_Ambiguous:
4193 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004194 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004195 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4196 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004197
4198 case OR_Deleted:
4199 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4200 << Best->Function->isDeleted()
4201 << UnqualifiedName
4202 << Fn->getSourceRange();
4203 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4204 break;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004205 }
4206
4207 // Overload resolution failed. Destroy all of the subexpressions and
4208 // return NULL.
4209 Fn->Destroy(Context);
4210 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4211 Args[Arg]->Destroy(Context);
4212 return 0;
4213}
4214
Douglas Gregorc78182d2009-03-13 23:49:33 +00004215/// \brief Create a unary operation that may resolve to an overloaded
4216/// operator.
4217///
4218/// \param OpLoc The location of the operator itself (e.g., '*').
4219///
4220/// \param OpcIn The UnaryOperator::Opcode that describes this
4221/// operator.
4222///
4223/// \param Functions The set of non-member functions that will be
4224/// considered by overload resolution. The caller needs to build this
4225/// set based on the context using, e.g.,
4226/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4227/// set should not contain any member functions; those will be added
4228/// by CreateOverloadedUnaryOp().
4229///
4230/// \param input The input argument.
4231Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4232 unsigned OpcIn,
4233 FunctionSet &Functions,
4234 ExprArg input) {
4235 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4236 Expr *Input = (Expr *)input.get();
4237
4238 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4239 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4240 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4241
4242 Expr *Args[2] = { Input, 0 };
4243 unsigned NumArgs = 1;
4244
4245 // For post-increment and post-decrement, add the implicit '0' as
4246 // the second argument, so that we know this is a post-increment or
4247 // post-decrement.
4248 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4249 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
4250 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
4251 SourceLocation());
4252 NumArgs = 2;
4253 }
4254
4255 if (Input->isTypeDependent()) {
4256 OverloadedFunctionDecl *Overloads
4257 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4258 for (FunctionSet::iterator Func = Functions.begin(),
4259 FuncEnd = Functions.end();
4260 Func != FuncEnd; ++Func)
4261 Overloads->addOverload(*Func);
4262
4263 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4264 OpLoc, false, false);
4265
4266 input.release();
4267 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4268 &Args[0], NumArgs,
4269 Context.DependentTy,
4270 OpLoc));
4271 }
4272
4273 // Build an empty overload set.
4274 OverloadCandidateSet CandidateSet;
4275
4276 // Add the candidates from the given function set.
4277 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4278
4279 // Add operator candidates that are member functions.
4280 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4281
4282 // Add builtin operator candidates.
4283 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4284
4285 // Perform overload resolution.
4286 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004287 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00004288 case OR_Success: {
4289 // We found a built-in operator or an overloaded operator.
4290 FunctionDecl *FnDecl = Best->Function;
4291
4292 if (FnDecl) {
4293 // We matched an overloaded operator. Build a call to that
4294 // operator.
4295
4296 // Convert the arguments.
4297 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4298 if (PerformObjectArgumentInitialization(Input, Method))
4299 return ExprError();
4300 } else {
4301 // Convert the arguments.
4302 if (PerformCopyInitialization(Input,
4303 FnDecl->getParamDecl(0)->getType(),
4304 "passing"))
4305 return ExprError();
4306 }
4307
4308 // Determine the result type
4309 QualType ResultTy
4310 = FnDecl->getType()->getAsFunctionType()->getResultType();
4311 ResultTy = ResultTy.getNonReferenceType();
4312
4313 // Build the actual expression node.
4314 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4315 SourceLocation());
4316 UsualUnaryConversions(FnExpr);
4317
4318 input.release();
Anders Carlsson16497742009-08-16 04:11:06 +00004319
4320 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4321 &Input, 1, ResultTy, OpLoc);
4322 return MaybeBindToTemporary(CE);
Douglas Gregorc78182d2009-03-13 23:49:33 +00004323 } else {
4324 // We matched a built-in operator. Convert the arguments, then
4325 // break out so that we will build the appropriate built-in
4326 // operator node.
4327 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4328 Best->Conversions[0], "passing"))
4329 return ExprError();
4330
4331 break;
4332 }
4333 }
4334
4335 case OR_No_Viable_Function:
4336 // No viable function; fall through to handling this as a
4337 // built-in operator, which will produce an error message for us.
4338 break;
4339
4340 case OR_Ambiguous:
4341 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4342 << UnaryOperator::getOpcodeStr(Opc)
4343 << Input->getSourceRange();
4344 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4345 return ExprError();
4346
4347 case OR_Deleted:
4348 Diag(OpLoc, diag::err_ovl_deleted_oper)
4349 << Best->Function->isDeleted()
4350 << UnaryOperator::getOpcodeStr(Opc)
4351 << Input->getSourceRange();
4352 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4353 return ExprError();
4354 }
4355
4356 // Either we found no viable overloaded operator or we matched a
4357 // built-in operator. In either case, fall through to trying to
4358 // build a built-in operation.
4359 input.release();
4360 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4361}
4362
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004363/// \brief Create a binary operation that may resolve to an overloaded
4364/// operator.
4365///
4366/// \param OpLoc The location of the operator itself (e.g., '+').
4367///
4368/// \param OpcIn The BinaryOperator::Opcode that describes this
4369/// operator.
4370///
4371/// \param Functions The set of non-member functions that will be
4372/// considered by overload resolution. The caller needs to build this
4373/// set based on the context using, e.g.,
4374/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4375/// set should not contain any member functions; those will be added
4376/// by CreateOverloadedBinOp().
4377///
4378/// \param LHS Left-hand argument.
4379/// \param RHS Right-hand argument.
4380Sema::OwningExprResult
4381Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
4382 unsigned OpcIn,
4383 FunctionSet &Functions,
4384 Expr *LHS, Expr *RHS) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004385 Expr *Args[2] = { LHS, RHS };
Douglas Gregor114c6192009-08-26 17:08:25 +00004386 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004387
4388 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4389 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4390 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4391
4392 // If either side is type-dependent, create an appropriate dependent
4393 // expression.
Douglas Gregor114c6192009-08-26 17:08:25 +00004394 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004395 // .* cannot be overloaded.
4396 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregor114c6192009-08-26 17:08:25 +00004397 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004398 Context.DependentTy, OpLoc));
4399
4400 OverloadedFunctionDecl *Overloads
4401 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4402 for (FunctionSet::iterator Func = Functions.begin(),
4403 FuncEnd = Functions.end();
4404 Func != FuncEnd; ++Func)
4405 Overloads->addOverload(*Func);
4406
4407 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4408 OpLoc, false, false);
4409
4410 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4411 Args, 2,
4412 Context.DependentTy,
4413 OpLoc));
4414 }
4415
4416 // If this is the .* operator, which is not overloadable, just
4417 // create a built-in binary operator.
4418 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregor114c6192009-08-26 17:08:25 +00004419 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004420
4421 // If this is one of the assignment operators, we only perform
4422 // overload resolution if the left-hand side is a class or
4423 // enumeration type (C++ [expr.ass]p3).
4424 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregor114c6192009-08-26 17:08:25 +00004425 !Args[0]->getType()->isOverloadableType())
4426 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004427
Douglas Gregorc78182d2009-03-13 23:49:33 +00004428 // Build an empty overload set.
4429 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004430
4431 // Add the candidates from the given function set.
4432 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4433
4434 // Add operator candidates that are member functions.
4435 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4436
4437 // Add builtin operator candidates.
4438 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4439
4440 // Perform overload resolution.
4441 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004442 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00004443 case OR_Success: {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004444 // We found a built-in operator or an overloaded operator.
4445 FunctionDecl *FnDecl = Best->Function;
4446
4447 if (FnDecl) {
4448 // We matched an overloaded operator. Build a call to that
4449 // operator.
4450
4451 // Convert the arguments.
4452 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregor114c6192009-08-26 17:08:25 +00004453 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4454 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004455 "passing"))
4456 return ExprError();
4457 } else {
4458 // Convert the arguments.
Douglas Gregor114c6192009-08-26 17:08:25 +00004459 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004460 "passing") ||
Douglas Gregor114c6192009-08-26 17:08:25 +00004461 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004462 "passing"))
4463 return ExprError();
4464 }
4465
4466 // Determine the result type
4467 QualType ResultTy
4468 = FnDecl->getType()->getAsFunctionType()->getResultType();
4469 ResultTy = ResultTy.getNonReferenceType();
4470
4471 // Build the actual expression node.
4472 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argiris Kirtzidiscca21b82009-07-14 03:19:38 +00004473 OpLoc);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004474 UsualUnaryConversions(FnExpr);
4475
Anders Carlsson16497742009-08-16 04:11:06 +00004476 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4477 Args, 2, ResultTy, OpLoc);
4478 return MaybeBindToTemporary(CE);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004479 } else {
4480 // We matched a built-in operator. Convert the arguments, then
4481 // break out so that we will build the appropriate built-in
4482 // operator node.
Douglas Gregor114c6192009-08-26 17:08:25 +00004483 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004484 Best->Conversions[0], "passing") ||
Douglas Gregor114c6192009-08-26 17:08:25 +00004485 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004486 Best->Conversions[1], "passing"))
4487 return ExprError();
4488
4489 break;
4490 }
4491 }
4492
4493 case OR_No_Viable_Function:
Sebastian Redl35196b42009-05-21 11:50:50 +00004494 // For class as left operand for assignment or compound assigment operator
4495 // do not fall through to handling in built-in, but report that no overloaded
4496 // assignment operator found
Douglas Gregor114c6192009-08-26 17:08:25 +00004497 if (Args[0]->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl35196b42009-05-21 11:50:50 +00004498 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4499 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor114c6192009-08-26 17:08:25 +00004500 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Sebastian Redl35196b42009-05-21 11:50:50 +00004501 return ExprError();
4502 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004503 // No viable function; fall through to handling this as a
4504 // built-in operator, which will produce an error message for us.
4505 break;
4506
4507 case OR_Ambiguous:
4508 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4509 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor114c6192009-08-26 17:08:25 +00004510 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004511 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4512 return ExprError();
4513
4514 case OR_Deleted:
4515 Diag(OpLoc, diag::err_ovl_deleted_oper)
4516 << Best->Function->isDeleted()
4517 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor114c6192009-08-26 17:08:25 +00004518 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004519 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4520 return ExprError();
4521 }
4522
4523 // Either we found no viable overloaded operator or we matched a
4524 // built-in operator. In either case, try to build a built-in
4525 // operation.
Douglas Gregor114c6192009-08-26 17:08:25 +00004526 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004527}
4528
Douglas Gregor3257fb52008-12-22 05:46:06 +00004529/// BuildCallToMemberFunction - Build a call to a member
4530/// function. MemExpr is the expression that refers to the member
4531/// function (and includes the object parameter), Args/NumArgs are the
4532/// arguments to the function call (not including the object
4533/// parameter). The caller needs to validate that the member
4534/// expression refers to a member function or an overloaded member
4535/// function.
4536Sema::ExprResult
4537Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4538 SourceLocation LParenLoc, Expr **Args,
4539 unsigned NumArgs, SourceLocation *CommaLocs,
4540 SourceLocation RParenLoc) {
4541 // Dig out the member expression. This holds both the object
4542 // argument and the member function we're referring to.
4543 MemberExpr *MemExpr = 0;
4544 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4545 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4546 else
4547 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4548 assert(MemExpr && "Building member call without member expression");
4549
4550 // Extract the object argument.
4551 Expr *ObjectArg = MemExpr->getBase();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00004552
Douglas Gregor3257fb52008-12-22 05:46:06 +00004553 CXXMethodDecl *Method = 0;
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004554 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4555 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00004556 // Add overload candidates
4557 OverloadCandidateSet CandidateSet;
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004558 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
4559
Douglas Gregor050cabf2009-08-21 18:42:58 +00004560 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4561 Func != FuncEnd; ++Func) {
4562 if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
4563 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
4564 /*SuppressUserConversions=*/false);
4565 else
4566 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4567 /*FIXME:*/false, /*FIXME:*/0,
4568 /*FIXME:*/0, ObjectArg, Args, NumArgs,
4569 CandidateSet,
4570 /*SuppressUsedConversions=*/false);
4571 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004572
Douglas Gregor3257fb52008-12-22 05:46:06 +00004573 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004574 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00004575 case OR_Success:
4576 Method = cast<CXXMethodDecl>(Best->Function);
4577 break;
4578
4579 case OR_No_Viable_Function:
4580 Diag(MemExpr->getSourceRange().getBegin(),
4581 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004582 << DeclName << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004583 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4584 // FIXME: Leaking incoming expressions!
4585 return true;
4586
4587 case OR_Ambiguous:
4588 Diag(MemExpr->getSourceRange().getBegin(),
4589 diag::err_ovl_ambiguous_member_call)
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004590 << DeclName << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004591 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4592 // FIXME: Leaking incoming expressions!
4593 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004594
4595 case OR_Deleted:
4596 Diag(MemExpr->getSourceRange().getBegin(),
4597 diag::err_ovl_deleted_member_call)
4598 << Best->Function->isDeleted()
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004599 << DeclName << MemExprE->getSourceRange();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004600 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4601 // FIXME: Leaking incoming expressions!
4602 return true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00004603 }
4604
4605 FixOverloadedFunctionReference(MemExpr, Method);
4606 } else {
4607 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4608 }
4609
4610 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek0c97e042009-02-07 01:47:29 +00004611 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek362abcd2009-02-09 20:51:47 +00004612 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
4613 NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00004614 Method->getResultType().getNonReferenceType(),
4615 RParenLoc));
4616
4617 // Convert the object argument (for a non-static member function call).
4618 if (!Method->isStatic() &&
4619 PerformObjectArgumentInitialization(ObjectArg, Method))
4620 return true;
4621 MemExpr->setBase(ObjectArg);
4622
4623 // Convert the rest of the arguments
Douglas Gregor4fa58902009-02-26 23:50:07 +00004624 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004625 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4626 RParenLoc))
4627 return true;
4628
Anders Carlsson7fb13802009-08-16 01:56:34 +00004629 if (CheckFunctionCall(Method, TheCall.get()))
4630 return true;
Anders Carlssonb8ff3402009-08-16 03:42:12 +00004631
4632 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004633}
4634
Douglas Gregor10f3c502008-11-19 21:05:33 +00004635/// BuildCallToObjectOfClassType - Build a call to an object of class
4636/// type (C++ [over.call.object]), which can end up invoking an
4637/// overloaded function call operator (@c operator()) or performing a
4638/// user-defined conversion on the object argument.
Douglas Gregor3257fb52008-12-22 05:46:06 +00004639Sema::ExprResult
Douglas Gregora133e262008-12-06 00:22:45 +00004640Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4641 SourceLocation LParenLoc,
Douglas Gregor10f3c502008-11-19 21:05:33 +00004642 Expr **Args, unsigned NumArgs,
4643 SourceLocation *CommaLocs,
4644 SourceLocation RParenLoc) {
4645 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004646 const RecordType *Record = Object->getType()->getAs<RecordType>();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004647
4648 // C++ [over.call.object]p1:
4649 // If the primary-expression E in the function call syntax
Eli Friedmand5a72f02009-08-05 19:21:58 +00004650 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor10f3c502008-11-19 21:05:33 +00004651 // candidate functions includes at least the function call
4652 // operators of T. The function call operators of T are obtained by
4653 // ordinary lookup of the name operator() in the context of
4654 // (E).operator().
4655 OverloadCandidateSet CandidateSet;
Douglas Gregor8acb7272008-12-11 16:49:14 +00004656 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004657 DeclContext::lookup_const_iterator Oper, OperEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00004658 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004659 Oper != OperEnd; ++Oper)
4660 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4661 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004662
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004663 // C++ [over.call.object]p2:
4664 // In addition, for each conversion function declared in T of the
4665 // form
4666 //
4667 // operator conversion-type-id () cv-qualifier;
4668 //
4669 // where cv-qualifier is the same cv-qualification as, or a
4670 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregor261afa72008-11-20 13:33:37 +00004671 // denotes the type "pointer to function of (P1,...,Pn) returning
4672 // R", or the type "reference to pointer to function of
4673 // (P1,...,Pn) returning R", or the type "reference to function
4674 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004675 // is also considered as a candidate function. Similarly,
4676 // surrogate call functions are added to the set of candidate
4677 // functions for each conversion function declared in an
4678 // accessible base class provided the function is not hidden
4679 // within T by another intervening declaration.
Douglas Gregorb35c7992009-08-24 15:23:48 +00004680
4681 if (!RequireCompleteType(SourceLocation(), Object->getType(), 0)) {
4682 // FIXME: Look in base classes for more conversion operators!
4683 OverloadedFunctionDecl *Conversions
4684 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
4685 for (OverloadedFunctionDecl::function_iterator
4686 Func = Conversions->function_begin(),
4687 FuncEnd = Conversions->function_end();
4688 Func != FuncEnd; ++Func) {
4689 CXXConversionDecl *Conv;
4690 FunctionTemplateDecl *ConvTemplate;
4691 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Douglas Gregor8c860df2009-08-21 23:19:43 +00004692
Douglas Gregorb35c7992009-08-24 15:23:48 +00004693 // Skip over templated conversion functions; they aren't
4694 // surrogates.
4695 if (ConvTemplate)
4696 continue;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004697
Douglas Gregorb35c7992009-08-24 15:23:48 +00004698 // Strip the reference type (if any) and then the pointer type (if
4699 // any) to get down to what might be a function type.
4700 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4701 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4702 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004703
Douglas Gregorb35c7992009-08-24 15:23:48 +00004704 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
4705 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4706 }
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004707 }
Douglas Gregorb35c7992009-08-24 15:23:48 +00004708
Douglas Gregor10f3c502008-11-19 21:05:33 +00004709 // Perform overload resolution.
4710 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004711 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004712 case OR_Success:
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004713 // Overload resolution succeeded; we'll build the appropriate call
4714 // below.
Douglas Gregor10f3c502008-11-19 21:05:33 +00004715 break;
4716
4717 case OR_No_Viable_Function:
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004718 Diag(Object->getSourceRange().getBegin(),
4719 diag::err_ovl_no_viable_object_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004720 << Object->getType() << Object->getSourceRange();
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004721 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004722 break;
4723
4724 case OR_Ambiguous:
4725 Diag(Object->getSourceRange().getBegin(),
4726 diag::err_ovl_ambiguous_object_call)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004727 << Object->getType() << Object->getSourceRange();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004728 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4729 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004730
4731 case OR_Deleted:
4732 Diag(Object->getSourceRange().getBegin(),
4733 diag::err_ovl_deleted_object_call)
4734 << Best->Function->isDeleted()
4735 << Object->getType() << Object->getSourceRange();
4736 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4737 break;
Douglas Gregor10f3c502008-11-19 21:05:33 +00004738 }
4739
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004740 if (Best == CandidateSet.end()) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004741 // We had an error; delete all of the subexpressions and return
4742 // the error.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004743 Object->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004744 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004745 Args[ArgIdx]->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004746 return true;
4747 }
4748
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004749 if (Best->Function == 0) {
4750 // Since there is no function declaration, this is one of the
4751 // surrogate candidates. Dig out the conversion function.
4752 CXXConversionDecl *Conv
4753 = cast<CXXConversionDecl>(
4754 Best->Conversions[0].UserDefined.ConversionFunction);
4755
4756 // We selected one of the surrogate functions that converts the
4757 // object parameter to a function pointer. Perform the conversion
4758 // on the object argument, then let ActOnCallExpr finish the job.
4759 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl8b769972009-01-19 00:08:26 +00004760 ImpCastExprToType(Object,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004761 Conv->getConversionType().getNonReferenceType(),
Anders Carlsson85186942009-07-31 01:23:52 +00004762 CastExpr::CK_Unknown,
Sebastian Redlce6fff02009-03-16 23:22:08 +00004763 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00004764 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4765 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4766 CommaLocs, RParenLoc).release();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004767 }
4768
4769 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4770 // that calls this method, using Object for the implicit object
4771 // parameter and passing along the remaining arguments.
4772 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004773 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004774
4775 unsigned NumArgsInProto = Proto->getNumArgs();
4776 unsigned NumArgsToCheck = NumArgs;
4777
4778 // Build the full argument list for the method call (the
4779 // implicit object parameter is placed at the beginning of the
4780 // list).
4781 Expr **MethodArgs;
4782 if (NumArgs < NumArgsInProto) {
4783 NumArgsToCheck = NumArgsInProto;
4784 MethodArgs = new Expr*[NumArgsInProto + 1];
4785 } else {
4786 MethodArgs = new Expr*[NumArgs + 1];
4787 }
4788 MethodArgs[0] = Object;
4789 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4790 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4791
Ted Kremenek0c97e042009-02-07 01:47:29 +00004792 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4793 SourceLocation());
Douglas Gregor10f3c502008-11-19 21:05:33 +00004794 UsualUnaryConversions(NewFn);
4795
4796 // Once we've built TheCall, all of the expressions are properly
4797 // owned.
4798 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00004799 ExprOwningPtr<CXXOperatorCallExpr>
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004800 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4801 MethodArgs, NumArgs + 1,
Ted Kremenek0c97e042009-02-07 01:47:29 +00004802 ResultTy, RParenLoc));
Douglas Gregor10f3c502008-11-19 21:05:33 +00004803 delete [] MethodArgs;
4804
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004805 // We may have default arguments. If so, we need to allocate more
4806 // slots in the call for them.
4807 if (NumArgs < NumArgsInProto)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004808 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004809 else if (NumArgs > NumArgsInProto)
4810 NumArgsToCheck = NumArgsInProto;
4811
Chris Lattner81f00ed2009-04-12 08:11:20 +00004812 bool IsError = false;
4813
Douglas Gregor10f3c502008-11-19 21:05:33 +00004814 // Initialize the implicit object parameter.
Chris Lattner81f00ed2009-04-12 08:11:20 +00004815 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004816 TheCall->setArg(0, Object);
4817
Chris Lattner81f00ed2009-04-12 08:11:20 +00004818
Douglas Gregor10f3c502008-11-19 21:05:33 +00004819 // Check the argument types.
4820 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004821 Expr *Arg;
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004822 if (i < NumArgs) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004823 Arg = Args[i];
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004824
4825 // Pass the argument.
4826 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner81f00ed2009-04-12 08:11:20 +00004827 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004828 } else {
Anders Carlsson3d752db2009-08-14 18:30:22 +00004829 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004830 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004831
4832 TheCall->setArg(i + 1, Arg);
4833 }
4834
4835 // If this is a variadic call, handle args passed through "...".
4836 if (Proto->isVariadic()) {
4837 // Promote the arguments (C99 6.5.2.2p7).
4838 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4839 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00004840 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004841 TheCall->setArg(i + 1, Arg);
4842 }
4843 }
4844
Chris Lattner81f00ed2009-04-12 08:11:20 +00004845 if (IsError) return true;
4846
Anders Carlsson7fb13802009-08-16 01:56:34 +00004847 if (CheckFunctionCall(Method, TheCall.get()))
4848 return true;
4849
Anders Carlsson422a5fe2009-08-16 03:53:54 +00004850 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004851}
4852
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004853/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4854/// (if one exists), where @c Base is an expression of class type and
4855/// @c Member is the name of the member we're trying to find.
Douglas Gregorda61ad22009-08-06 03:17:00 +00004856Sema::OwningExprResult
4857Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
4858 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004859 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4860
4861 // C++ [over.ref]p1:
4862 //
4863 // [...] An expression x->m is interpreted as (x.operator->())->m
4864 // for a class object x of type T if T::operator->() exists and if
4865 // the operator is selected as the best match function by the
4866 // overload resolution mechanism (13.3).
4867 // FIXME: look in base classes.
4868 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4869 OverloadCandidateSet CandidateSet;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004870 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorda61ad22009-08-06 03:17:00 +00004871
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004872 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004873 for (llvm::tie(Oper, OperEnd)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00004874 = BaseRecord->getDecl()->lookup(OpName); Oper != OperEnd; ++Oper)
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004875 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004876 /*SuppressUserConversions=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004877
4878 // Perform overload resolution.
4879 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004880 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004881 case OR_Success:
4882 // Overload resolution succeeded; we'll build the call below.
4883 break;
4884
4885 case OR_No_Viable_Function:
4886 if (CandidateSet.empty())
4887 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004888 << Base->getType() << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004889 else
4890 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004891 << "operator->" << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004892 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004893 return ExprError();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004894
4895 case OR_Ambiguous:
4896 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004897 << "operator->" << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004898 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004899 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004900
4901 case OR_Deleted:
4902 Diag(OpLoc, diag::err_ovl_deleted_oper)
4903 << Best->Function->isDeleted()
Douglas Gregorda61ad22009-08-06 03:17:00 +00004904 << "operator->" << Base->getSourceRange();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004905 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004906 return ExprError();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004907 }
4908
4909 // Convert the object parameter.
4910 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004911 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorda61ad22009-08-06 03:17:00 +00004912 return ExprError();
Douglas Gregor9c690e92008-11-21 03:04:22 +00004913
4914 // No concerns about early exits now.
Douglas Gregorda61ad22009-08-06 03:17:00 +00004915 BaseIn.release();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004916
4917 // Build the operator call.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004918 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4919 SourceLocation());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004920 UsualUnaryConversions(FnExpr);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004921 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004922 Method->getResultType().getNonReferenceType(),
4923 OpLoc);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004924 return Owned(Base);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004925}
4926
Douglas Gregor45014fd2008-11-10 20:40:00 +00004927/// FixOverloadedFunctionReference - E is an expression that refers to
4928/// a C++ overloaded function (possibly with some parentheses and
4929/// perhaps a '&' around it). We have resolved the overloaded function
4930/// to the function declaration Fn, so patch up the expression E to
4931/// refer (possibly indirectly) to Fn.
4932void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4933 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4934 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4935 E->setType(PE->getSubExpr()->getType());
4936 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4937 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4938 "Can only take the address of an overloaded function");
Douglas Gregor3f411962009-02-11 01:18:59 +00004939 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4940 if (Method->isStatic()) {
4941 // Do nothing: static member functions aren't any different
4942 // from non-member functions.
Mike Stump90fc78e2009-08-04 21:02:39 +00004943 } else if (QualifiedDeclRefExpr *DRE
Douglas Gregor3f411962009-02-11 01:18:59 +00004944 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4945 // We have taken the address of a pointer to member
4946 // function. Perform the computation here so that we get the
4947 // appropriate pointer to member type.
4948 DRE->setDecl(Fn);
4949 DRE->setType(Fn->getType());
4950 QualType ClassType
4951 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4952 E->setType(Context.getMemberPointerType(Fn->getType(),
4953 ClassType.getTypePtr()));
4954 return;
4955 }
4956 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00004957 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor2eedd992009-02-11 00:19:33 +00004958 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor45014fd2008-11-10 20:40:00 +00004959 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor62f78762009-07-08 20:55:45 +00004960 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
4961 isa<FunctionTemplateDecl>(DR->getDecl())) &&
4962 "Expected overloaded function or function template");
Douglas Gregor45014fd2008-11-10 20:40:00 +00004963 DR->setDecl(Fn);
4964 E->setType(Fn->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004965 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4966 MemExpr->setMemberDecl(Fn);
4967 E->setType(Fn->getType());
Douglas Gregor45014fd2008-11-10 20:40:00 +00004968 } else {
4969 assert(false && "Invalid reference to overloaded function");
4970 }
4971}
4972
Douglas Gregord2baafd2008-10-21 16:13:35 +00004973} // end namespace clang