blob: 5e9d101d385be22e474f8113a2bf6dcb944088ab [file] [log] [blame]
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000020#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000022#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000024#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000025#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000026#include "llvm/Support/Compiler.h"
27#include <algorithm>
Torok Edwinf42e4a62009-08-24 13:25:12 +000028#include <cstdio>
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000029
30namespace clang {
31
32/// GetConversionCategory - Retrieve the implicit conversion
33/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000034ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000035GetConversionCategory(ImplicitConversionKind Kind) {
36 static const ImplicitConversionCategory
37 Category[(int)ICK_Num_Conversion_Kinds] = {
38 ICC_Identity,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
41 ICC_Lvalue_Transformation,
42 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000055 ICC_Conversion
56 };
57 return Category[(int)Kind];
58}
59
60/// GetConversionRank - Retrieve the implicit conversion rank
61/// corresponding to the given implicit conversion kind.
62ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
63 static const ImplicitConversionRank
64 Rank[(int)ICK_Num_Conversion_Kinds] = {
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
70 ICR_Promotion,
71 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000072 ICR_Promotion,
73 ICR_Conversion,
74 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000075 ICR_Conversion,
76 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000080 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000081 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000082 ICR_Conversion
83 };
84 return Rank[(int)Kind];
85}
86
87/// GetImplicitConversionName - Return the name of this kind of
88/// implicit conversion.
89const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
90 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
91 "No conversion",
92 "Lvalue-to-rvalue",
93 "Array-to-pointer",
94 "Function-to-pointer",
95 "Qualification",
96 "Integral promotion",
97 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +000098 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000099 "Integral conversion",
100 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000101 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000102 "Floating-integral conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000103 "Complex-real conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000104 "Pointer conversion",
105 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000106 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000107 "Compatible-types conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000108 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000109 };
110 return Name[Kind];
111}
112
Douglas Gregor60d62c22008-10-31 16:23:19 +0000113/// StandardConversionSequence - Set the standard conversion
114/// sequence to the identity conversion.
115void StandardConversionSequence::setAsIdentityConversion() {
116 First = ICK_Identity;
117 Second = ICK_Identity;
118 Third = ICK_Identity;
119 Deprecated = false;
120 ReferenceBinding = false;
121 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000122 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000123 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000124}
125
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000126/// getRank - Retrieve the rank of this standard conversion sequence
127/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
128/// implicit conversions.
129ImplicitConversionRank StandardConversionSequence::getRank() const {
130 ImplicitConversionRank Rank = ICR_Exact_Match;
131 if (GetConversionRank(First) > Rank)
132 Rank = GetConversionRank(First);
133 if (GetConversionRank(Second) > Rank)
134 Rank = GetConversionRank(Second);
135 if (GetConversionRank(Third) > Rank)
136 Rank = GetConversionRank(Third);
137 return Rank;
138}
139
140/// isPointerConversionToBool - Determines whether this conversion is
141/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000142/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000143/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000144bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000145 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 Gregor2a7e58d2008-12-23 00:53:59 +0000153 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-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 Gregorbc0805a2008-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).
Mike Stump1eb44332009-09-09 15:08:12 +0000164bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000165StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000166isPointerConversionToVoidPointer(ASTContext& Context) const {
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000167 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
168 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
169
170 // Note that FromType has not necessarily been transformed by the
171 // array-to-pointer implicit conversion, so check for its presence
172 // and redo the conversion to get a pointer.
173 if (First == ICK_Array_To_Pointer)
174 FromType = Context.getArrayDecayedType(FromType);
175
176 if (Second == ICK_Pointer_Conversion)
Ted Kremenek6217b802009-07-29 21:53:49 +0000177 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000178 return ToPtrType->getPointeeType()->isVoidType();
179
180 return false;
181}
182
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000183/// DebugPrint - Print this standard conversion sequence to standard
184/// error. Useful for debugging overloading issues.
185void StandardConversionSequence::DebugPrint() const {
186 bool PrintedSomething = false;
187 if (First != ICK_Identity) {
188 fprintf(stderr, "%s", GetImplicitConversionName(First));
189 PrintedSomething = true;
190 }
191
192 if (Second != ICK_Identity) {
193 if (PrintedSomething) {
194 fprintf(stderr, " -> ");
195 }
196 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor225c41e2008-11-03 19:09:14 +0000197
198 if (CopyConstructor) {
199 fprintf(stderr, " (by copy constructor)");
200 } else if (DirectBinding) {
201 fprintf(stderr, " (direct reference binding)");
202 } else if (ReferenceBinding) {
203 fprintf(stderr, " (reference binding)");
204 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000205 PrintedSomething = true;
206 }
207
208 if (Third != ICK_Identity) {
209 if (PrintedSomething) {
210 fprintf(stderr, " -> ");
211 }
212 fprintf(stderr, "%s", GetImplicitConversionName(Third));
213 PrintedSomething = true;
214 }
215
216 if (!PrintedSomething) {
217 fprintf(stderr, "No conversions required");
218 }
219}
220
221/// DebugPrint - Print this user-defined conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void UserDefinedConversionSequence::DebugPrint() const {
224 if (Before.First || Before.Second || Before.Third) {
225 Before.DebugPrint();
226 fprintf(stderr, " -> ");
227 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000228 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000229 if (After.First || After.Second || After.Third) {
230 fprintf(stderr, " -> ");
231 After.DebugPrint();
232 }
233}
234
235/// DebugPrint - Print this implicit conversion sequence to standard
236/// error. Useful for debugging overloading issues.
237void ImplicitConversionSequence::DebugPrint() const {
238 switch (ConversionKind) {
239 case StandardConversion:
240 fprintf(stderr, "Standard conversion: ");
241 Standard.DebugPrint();
242 break;
243 case UserDefinedConversion:
244 fprintf(stderr, "User-defined conversion: ");
245 UserDefined.DebugPrint();
246 break;
247 case EllipsisConversion:
248 fprintf(stderr, "Ellipsis conversion");
249 break;
250 case BadConversion:
251 fprintf(stderr, "Bad conversion");
252 break;
253 }
254
255 fprintf(stderr, "\n");
256}
257
258// IsOverload - Determine whether the given New declaration is an
259// overload of the Old declaration. This routine returns false if New
260// and Old cannot be overloaded, e.g., if they are functions with the
261// same signature (C++ 1.3.10) or if the Old declaration isn't a
262// function (or overload set). When it does return false and Old is an
263// OverloadedFunctionDecl, MatchedDecl will be set to point to the
Mike Stump1eb44332009-09-09 15:08:12 +0000264// FunctionDecl that New cannot be overloaded with.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000265//
266// Example: Given the following input:
267//
268// void f(int, float); // #1
269// void f(int, int); // #2
270// int f(int, int); // #3
271//
272// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000273// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000274//
275// When we process #2, Old is a FunctionDecl for #1. By comparing the
276// parameter types, we see that #1 and #2 are overloaded (since they
277// have different signatures), so this routine returns false;
278// MatchedDecl is unchanged.
279//
280// When we process #3, Old is an OverloadedFunctionDecl containing #1
281// and #2. We compare the signatures of #3 to #1 (they're overloaded,
282// so we do nothing) and then #3 to #2. Since the signatures of #3 and
283// #2 are identical (return types of functions are not part of the
284// signature), IsOverload returns false and MatchedDecl will be set to
285// point to the FunctionDecl for #2.
286bool
John McCall68263142009-11-18 22:49:29 +0000287Sema::IsOverload(FunctionDecl *New, LookupResult &Previous, NamedDecl *&Match) {
288 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
289 I != E; ++I) {
290 NamedDecl *Old = (*I)->getUnderlyingDecl();
291 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(Old)) {
292 if (!IsOverload(New, OldT->getTemplatedDecl())) {
293 Match = Old;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000294 return false;
295 }
John McCall68263142009-11-18 22:49:29 +0000296 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(Old)) {
297 if (!IsOverload(New, OldF)) {
298 Match = Old;
299 return false;
300 }
301 } else {
302 // (C++ 13p1):
303 // Only function declarations can be overloaded; object and type
304 // declarations cannot be overloaded.
305 Match = Old;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000306 return false;
John McCall68263142009-11-18 22:49:29 +0000307 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000308 }
John McCall68263142009-11-18 22:49:29 +0000309
310 return true;
311}
312
313bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
314 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
315 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
316
317 // C++ [temp.fct]p2:
318 // A function template can be overloaded with other function templates
319 // and with normal (non-template) functions.
320 if ((OldTemplate == 0) != (NewTemplate == 0))
321 return true;
322
323 // Is the function New an overload of the function Old?
324 QualType OldQType = Context.getCanonicalType(Old->getType());
325 QualType NewQType = Context.getCanonicalType(New->getType());
326
327 // Compare the signatures (C++ 1.3.10) of the two functions to
328 // determine whether they are overloads. If we find any mismatch
329 // in the signature, they are overloads.
330
331 // If either of these functions is a K&R-style function (no
332 // prototype), then we consider them to have matching signatures.
333 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
334 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
335 return false;
336
337 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
338 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
339
340 // The signature of a function includes the types of its
341 // parameters (C++ 1.3.10), which includes the presence or absence
342 // of the ellipsis; see C++ DR 357).
343 if (OldQType != NewQType &&
344 (OldType->getNumArgs() != NewType->getNumArgs() ||
345 OldType->isVariadic() != NewType->isVariadic() ||
346 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
347 NewType->arg_type_begin())))
348 return true;
349
350 // C++ [temp.over.link]p4:
351 // The signature of a function template consists of its function
352 // signature, its return type and its template parameter list. The names
353 // of the template parameters are significant only for establishing the
354 // relationship between the template parameters and the rest of the
355 // signature.
356 //
357 // We check the return type and template parameter lists for function
358 // templates first; the remaining checks follow.
359 if (NewTemplate &&
360 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
361 OldTemplate->getTemplateParameters(),
362 false, TPL_TemplateMatch) ||
363 OldType->getResultType() != NewType->getResultType()))
364 return true;
365
366 // If the function is a class member, its signature includes the
367 // cv-qualifiers (if any) on the function itself.
368 //
369 // As part of this, also check whether one of the member functions
370 // is static, in which case they are not overloads (C++
371 // 13.1p2). While not part of the definition of the signature,
372 // this check is important to determine whether these functions
373 // can be overloaded.
374 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
375 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
376 if (OldMethod && NewMethod &&
377 !OldMethod->isStatic() && !NewMethod->isStatic() &&
378 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
379 return true;
380
381 // The signatures match; this is not an overload.
382 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000383}
384
Douglas Gregor27c8dc02008-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 Gregor8e9bebd2008-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 Gregor225c41e2008-11-03 19:09:14 +0000403///
404/// If @p SuppressUserConversions, then user-defined conversions are
405/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000406/// If @p AllowExplicit, then explicit user-defined conversions are
407/// permitted.
Sebastian Redle2b68332009-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.
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000410/// If @p UserCast, the implicit conversion is being done for a user-specified
411/// cast.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000412ImplicitConversionSequence
Anders Carlsson2974b5c2009-08-27 17:14:02 +0000413Sema::TryImplicitConversion(Expr* From, QualType ToType,
414 bool SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +0000415 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000416 bool InOverloadResolution,
417 bool UserCast) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000418 ImplicitConversionSequence ICS;
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +0000419 OverloadCandidateSet Conversions;
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000420 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson08972922009-08-28 15:33:32 +0000421 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor60d62c22008-10-31 16:23:19 +0000422 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000423 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000424 (UserDefResult = IsUserDefinedConversion(From, ToType,
425 ICS.UserDefined,
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +0000426 Conversions,
Sebastian Redle2b68332009-04-12 17:16:29 +0000427 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000428 ForceRValue, UserCast)) == OR_Success) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000429 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000430 // C++ [over.ics.user]p4:
431 // A conversion of an expression of class type to the same class
432 // type is given Exact Match rank, and a conversion of an
433 // expression of class type to a base class of that type is
434 // given Conversion rank, in spite of the fact that a copy
435 // constructor (i.e., a user-defined conversion function) is
436 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000437 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000438 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000439 QualType FromCanon
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000440 = Context.getCanonicalType(From->getType().getUnqualifiedType());
441 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
442 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000443 // Turn this into a "standard" conversion sequence, so that it
444 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000445 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
446 ICS.Standard.setAsIdentityConversion();
447 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
448 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000449 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000450 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000451 ICS.Standard.Second = ICK_Derived_To_Base;
452 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000453 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000454
455 // C++ [over.best.ics]p4:
456 // However, when considering the argument of a user-defined
457 // conversion function that is a candidate by 13.3.1.3 when
458 // invoked for the copying of the temporary in the second step
459 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
460 // 13.3.1.6 in all cases, only standard conversion sequences and
461 // ellipsis conversion sequences are allowed.
462 if (SuppressUserConversions &&
463 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
464 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000465 } else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000466 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000467 if (UserDefResult == OR_Ambiguous) {
468 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
469 Cand != Conversions.end(); ++Cand)
Fariborz Jahanian27687cf2009-10-12 17:51:19 +0000470 if (Cand->Viable)
471 ICS.ConversionFunctionSet.push_back(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000472 }
473 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000474
475 return ICS;
476}
477
478/// IsStandardConversion - Determines whether there is a standard
479/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
480/// expression From to the type ToType. Standard conversion sequences
481/// only consider non-class types; for conversions that involve class
482/// types, use TryImplicitConversion. If a conversion exists, SCS will
483/// contain the standard conversion sequence required to perform this
484/// conversion and this routine will return true. Otherwise, this
485/// routine will return false and the value of SCS is unspecified.
Mike Stump1eb44332009-09-09 15:08:12 +0000486bool
487Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000488 bool InOverloadResolution,
Mike Stump1eb44332009-09-09 15:08:12 +0000489 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000490 QualType FromType = From->getType();
491
Douglas Gregor60d62c22008-10-31 16:23:19 +0000492 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000493 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000494 SCS.Deprecated = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000495 SCS.IncompatibleObjC = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000496 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000497 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000498
Douglas Gregorf9201e02009-02-11 23:02:49 +0000499 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000500 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000501 if (FromType->isRecordType() || ToType->isRecordType()) {
502 if (getLangOptions().CPlusPlus)
503 return false;
504
Mike Stump1eb44332009-09-09 15:08:12 +0000505 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000506 }
507
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000508 // The first conversion can be an lvalue-to-rvalue conversion,
509 // array-to-pointer conversion, or function-to-pointer conversion
510 // (C++ 4p1).
511
Mike Stump1eb44332009-09-09 15:08:12 +0000512 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000513 // An lvalue (3.10) of a non-function, non-array type T can be
514 // converted to an rvalue.
515 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000516 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000517 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000518 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000519 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000520
521 // If T is a non-class type, the type of the rvalue is the
522 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000523 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
524 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000525 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000526 } else if (FromType->isArrayType()) {
527 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000528 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000529
530 // An lvalue or rvalue of type "array of N T" or "array of unknown
531 // bound of T" can be converted to an rvalue of type "pointer to
532 // T" (C++ 4.2p1).
533 FromType = Context.getArrayDecayedType(FromType);
534
535 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
536 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000537 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000538
539 // For the purpose of ranking in overload resolution
540 // (13.3.3.1.1), this conversion is considered an
541 // array-to-pointer conversion followed by a qualification
542 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000543 SCS.Second = ICK_Identity;
544 SCS.Third = ICK_Qualification;
545 SCS.ToTypePtr = ToType.getAsOpaquePtr();
546 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000547 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000548 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
549 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000550 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000551
552 // An lvalue of function type T can be converted to an rvalue of
553 // type "pointer to T." The result is a pointer to the
554 // function. (C++ 4.3p1).
555 FromType = Context.getPointerType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000556 } else if (FunctionDecl *Fn
Douglas Gregor904eed32008-11-10 20:40:00 +0000557 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000558 // Address of overloaded function (C++ [over.over]).
Douglas Gregor904eed32008-11-10 20:40:00 +0000559 SCS.First = ICK_Function_To_Pointer;
560
561 // We were able to resolve the address of the overloaded function,
562 // so we can convert to the type of that function.
563 FromType = Fn->getType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000564 if (ToType->isLValueReferenceType())
565 FromType = Context.getLValueReferenceType(FromType);
566 else if (ToType->isRValueReferenceType())
567 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000568 else if (ToType->isMemberPointerType()) {
569 // Resolve address only succeeds if both sides are member pointers,
570 // but it doesn't have to be the same class. See DR 247.
571 // Note that this means that the type of &Derived::fn can be
572 // Ret (Base::*)(Args) if the fn overload actually found is from the
573 // base class, even if it was brought into the derived class via a
574 // using declaration. The standard isn't clear on this issue at all.
575 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
576 FromType = Context.getMemberPointerType(FromType,
577 Context.getTypeDeclType(M->getParent()).getTypePtr());
578 } else
Douglas Gregor904eed32008-11-10 20:40:00 +0000579 FromType = Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000580 } else {
581 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000582 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000583 }
584
585 // The second conversion can be an integral promotion, floating
586 // point promotion, integral conversion, floating point conversion,
587 // floating-integral conversion, pointer conversion,
588 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000589 // For overloading in C, this can also be a "compatible-type"
590 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000591 bool IncompatibleObjC = false;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000592 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000593 // The unqualified versions of the types are the same: there's no
594 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000595 SCS.Second = ICK_Identity;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000596 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000597 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000598 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000599 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000600 } else if (IsFloatingPointPromotion(FromType, ToType)) {
601 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000602 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000603 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000604 } else if (IsComplexPromotion(FromType, ToType)) {
605 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000606 SCS.Second = ICK_Complex_Promotion;
607 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000608 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000609 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000610 // Integral conversions (C++ 4.7).
611 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000612 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000613 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000614 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
615 // Floating point conversions (C++ 4.8).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000616 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000617 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000618 } else if (FromType->isComplexType() && ToType->isComplexType()) {
619 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000620 SCS.Second = ICK_Complex_Conversion;
621 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000622 } else if ((FromType->isFloatingType() &&
623 ToType->isIntegralType() && (!ToType->isBooleanType() &&
624 !ToType->isEnumeralType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000625 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000626 ToType->isFloatingType())) {
627 // Floating-integral conversions (C++ 4.9).
628 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000629 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000630 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000631 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
632 (ToType->isComplexType() && FromType->isArithmeticType())) {
633 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000634 SCS.Second = ICK_Complex_Real;
635 FromType = ToType.getUnqualifiedType();
Anders Carlsson08972922009-08-28 15:33:32 +0000636 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
637 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000638 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000639 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000640 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregorce940492009-09-25 04:25:58 +0000641 } else if (IsMemberPointerConversion(From, FromType, ToType,
642 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000643 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000644 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000645 } else if (ToType->isBooleanType() &&
646 (FromType->isArithmeticType() ||
647 FromType->isEnumeralType() ||
648 FromType->isPointerType() ||
649 FromType->isBlockPointerType() ||
650 FromType->isMemberPointerType() ||
651 FromType->isNullPtrType())) {
652 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000653 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000654 FromType = Context.BoolTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000655 } else if (!getLangOptions().CPlusPlus &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000656 Context.typesAreCompatible(ToType, FromType)) {
657 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000658 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000659 } else {
660 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000661 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000662 }
663
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000664 QualType CanonFrom;
665 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000666 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000667 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000668 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000669 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000670 CanonFrom = Context.getCanonicalType(FromType);
671 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000672 } else {
673 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000674 SCS.Third = ICK_Identity;
675
Mike Stump1eb44332009-09-09 15:08:12 +0000676 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +0000677 // [...] Any difference in top-level cv-qualification is
678 // subsumed by the initialization itself and does not constitute
679 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000680 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000681 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +0000682 if (CanonFrom.getLocalUnqualifiedType()
683 == CanonTo.getLocalUnqualifiedType() &&
684 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000685 FromType = ToType;
686 CanonFrom = CanonTo;
687 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000688 }
689
690 // If we have not converted the argument type to the parameter type,
691 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000692 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000693 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000694
Douglas Gregor60d62c22008-10-31 16:23:19 +0000695 SCS.ToTypePtr = FromType.getAsOpaquePtr();
696 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000697}
698
699/// IsIntegralPromotion - Determines whether the conversion from the
700/// expression From (whose potentially-adjusted type is FromType) to
701/// ToType is an integral promotion (C++ 4.5). If so, returns true and
702/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000703bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000704 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000705 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000706 if (!To) {
707 return false;
708 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000709
710 // An rvalue of type char, signed char, unsigned char, short int, or
711 // unsigned short int can be converted to an rvalue of type int if
712 // int can represent all the values of the source type; otherwise,
713 // the source rvalue can be converted to an rvalue of type unsigned
714 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000715 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000716 if (// We can promote any signed, promotable integer type to an int
717 (FromType->isSignedIntegerType() ||
718 // We can promote any unsigned integer type whose size is
719 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +0000720 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000721 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000722 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000723 }
724
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000725 return To->getKind() == BuiltinType::UInt;
726 }
727
728 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
729 // can be converted to an rvalue of the first of the following types
730 // that can represent all the values of its underlying type: int,
731 // unsigned int, long, or unsigned long (C++ 4.5p2).
732 if ((FromType->isEnumeralType() || FromType->isWideCharType())
733 && ToType->isIntegerType()) {
734 // Determine whether the type we're converting from is signed or
735 // unsigned.
736 bool FromIsSigned;
737 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall183700f2009-09-21 23:43:11 +0000738 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000739 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
740 FromIsSigned = UnderlyingType->isSignedIntegerType();
741 } else {
742 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
743 FromIsSigned = true;
744 }
745
746 // The types we'll try to promote to, in the appropriate
747 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +0000748 QualType PromoteTypes[6] = {
749 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000750 Context.LongTy, Context.UnsignedLongTy ,
751 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000752 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000753 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000754 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
755 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +0000756 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000757 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
758 // We found the type that we can promote to. If this is the
759 // type we wanted, we have a promotion. Otherwise, no
760 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000761 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000762 }
763 }
764 }
765
766 // An rvalue for an integral bit-field (9.6) can be converted to an
767 // rvalue of type int if int can represent all the values of the
768 // bit-field; otherwise, it can be converted to unsigned int if
769 // unsigned int can represent all the values of the bit-field. If
770 // the bit-field is larger yet, no integral promotion applies to
771 // it. If the bit-field has an enumerated type, it is treated as any
772 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +0000773 // FIXME: We should delay checking of bit-fields until we actually perform the
774 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000775 using llvm::APSInt;
776 if (From)
777 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +0000778 APSInt BitWidth;
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000779 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
780 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
781 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
782 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Douglas Gregor86f19402008-12-20 23:49:58 +0000784 // Are we promoting to an int from a bitfield that fits in an int?
785 if (BitWidth < ToSize ||
786 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
787 return To->getKind() == BuiltinType::Int;
788 }
Mike Stump1eb44332009-09-09 15:08:12 +0000789
Douglas Gregor86f19402008-12-20 23:49:58 +0000790 // Are we promoting to an unsigned int from an unsigned bitfield
791 // that fits into an unsigned int?
792 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
793 return To->getKind() == BuiltinType::UInt;
794 }
Mike Stump1eb44332009-09-09 15:08:12 +0000795
Douglas Gregor86f19402008-12-20 23:49:58 +0000796 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000797 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000798 }
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000800 // An rvalue of type bool can be converted to an rvalue of type int,
801 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000802 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000803 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000804 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000805
806 return false;
807}
808
809/// IsFloatingPointPromotion - Determines whether the conversion from
810/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
811/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000812bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000813 /// An rvalue of type float can be converted to an rvalue of type
814 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +0000815 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
816 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000817 if (FromBuiltin->getKind() == BuiltinType::Float &&
818 ToBuiltin->getKind() == BuiltinType::Double)
819 return true;
820
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000821 // C99 6.3.1.5p1:
822 // When a float is promoted to double or long double, or a
823 // double is promoted to long double [...].
824 if (!getLangOptions().CPlusPlus &&
825 (FromBuiltin->getKind() == BuiltinType::Float ||
826 FromBuiltin->getKind() == BuiltinType::Double) &&
827 (ToBuiltin->getKind() == BuiltinType::LongDouble))
828 return true;
829 }
830
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000831 return false;
832}
833
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000834/// \brief Determine if a conversion is a complex promotion.
835///
836/// A complex promotion is defined as a complex -> complex conversion
837/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000838/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000839bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000840 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000841 if (!FromComplex)
842 return false;
843
John McCall183700f2009-09-21 23:43:11 +0000844 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000845 if (!ToComplex)
846 return false;
847
848 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000849 ToComplex->getElementType()) ||
850 IsIntegralPromotion(0, FromComplex->getElementType(),
851 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000852}
853
Douglas Gregorcb7de522008-11-26 23:31:11 +0000854/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
855/// the pointer type FromPtr to a pointer to type ToPointee, with the
856/// same type qualifiers as FromPtr has on its pointee type. ToType,
857/// if non-empty, will be a pointer to ToType that may or may not have
858/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +0000859static QualType
860BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000861 QualType ToPointee, QualType ToType,
862 ASTContext &Context) {
863 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
864 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +0000865 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +0000866
867 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000868 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +0000869 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +0000870 if (!ToType.isNull())
Douglas Gregorcb7de522008-11-26 23:31:11 +0000871 return ToType;
872
873 // Build a pointer to ToPointee. It has the right qualifiers
874 // already.
875 return Context.getPointerType(ToPointee);
876 }
877
878 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +0000879 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +0000880 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
881 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +0000882}
883
Mike Stump1eb44332009-09-09 15:08:12 +0000884static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000885 bool InOverloadResolution,
886 ASTContext &Context) {
887 // Handle value-dependent integral null pointer constants correctly.
888 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
889 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
890 Expr->getType()->isIntegralType())
891 return !InOverloadResolution;
892
Douglas Gregorce940492009-09-25 04:25:58 +0000893 return Expr->isNullPointerConstant(Context,
894 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
895 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000896}
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000898/// IsPointerConversion - Determines whether the conversion of the
899/// expression From, which has the (possibly adjusted) type FromType,
900/// can be converted to the type ToType via a pointer conversion (C++
901/// 4.10). If so, returns true and places the converted type (that
902/// might differ from ToType in its cv-qualifiers at some level) into
903/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000904///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000905/// This routine also supports conversions to and from block pointers
906/// and conversions with Objective-C's 'id', 'id<protocols...>', and
907/// pointers to interfaces. FIXME: Once we've determined the
908/// appropriate overloading rules for Objective-C, we may want to
909/// split the Objective-C checks into a different routine; however,
910/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000911/// conversions, so for now they live here. IncompatibleObjC will be
912/// set if the conversion is an allowed Objective-C conversion that
913/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000914bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000915 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +0000916 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +0000917 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +0000918 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000919 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
920 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000921
Mike Stump1eb44332009-09-09 15:08:12 +0000922 // Conversion from a null pointer constant to any Objective-C pointer type.
923 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000924 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +0000925 ConvertedType = ToType;
926 return true;
927 }
928
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000929 // Blocks: Block pointers can be converted to void*.
930 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000931 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000932 ConvertedType = ToType;
933 return true;
934 }
935 // Blocks: A null pointer constant can be converted to a block
936 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +0000937 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000938 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000939 ConvertedType = ToType;
940 return true;
941 }
942
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000943 // If the left-hand-side is nullptr_t, the right side can be a null
944 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +0000945 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000946 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000947 ConvertedType = ToType;
948 return true;
949 }
950
Ted Kremenek6217b802009-07-29 21:53:49 +0000951 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000952 if (!ToTypePtr)
953 return false;
954
955 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000956 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000957 ConvertedType = ToType;
958 return true;
959 }
Sebastian Redl07779722008-10-31 14:43:28 +0000960
Douglas Gregorcb7de522008-11-26 23:31:11 +0000961 // Beyond this point, both types need to be pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +0000962 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +0000963 if (!FromTypePtr)
964 return false;
965
966 QualType FromPointeeType = FromTypePtr->getPointeeType();
967 QualType ToPointeeType = ToTypePtr->getPointeeType();
968
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000969 // An rvalue of type "pointer to cv T," where T is an object type,
970 // can be converted to an rvalue of type "pointer to cv void" (C++
971 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +0000972 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000973 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +0000974 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000975 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000976 return true;
977 }
978
Douglas Gregorf9201e02009-02-11 23:02:49 +0000979 // When we're overloading in C, we allow a special kind of pointer
980 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +0000981 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +0000982 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000983 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000984 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +0000985 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +0000986 return true;
987 }
988
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000989 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +0000990 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000991 // An rvalue of type "pointer to cv D," where D is a class type,
992 // can be converted to an rvalue of type "pointer to cv B," where
993 // B is a base class (clause 10) of D. If B is an inaccessible
994 // (clause 11) or ambiguous (10.2) base class of D, a program that
995 // necessitates this conversion is ill-formed. The result of the
996 // conversion is a pointer to the base class sub-object of the
997 // derived class object. The null pointer value is converted to
998 // the null pointer value of the destination type.
999 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001000 // Note that we do not check for ambiguity or inaccessibility
1001 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001002 if (getLangOptions().CPlusPlus &&
1003 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001004 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001005 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001006 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001007 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001008 ToType, Context);
1009 return true;
1010 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001011
Douglas Gregorc7887512008-12-19 19:13:09 +00001012 return false;
1013}
1014
1015/// isObjCPointerConversion - Determines whether this is an
1016/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1017/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001018bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001019 QualType& ConvertedType,
1020 bool &IncompatibleObjC) {
1021 if (!getLangOptions().ObjC1)
1022 return false;
1023
Steve Naroff14108da2009-07-10 23:34:53 +00001024 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001025 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001026 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001027 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001028
Steve Naroff14108da2009-07-10 23:34:53 +00001029 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001030 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001031 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001032 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001033 ConvertedType = ToType;
1034 return true;
1035 }
1036 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001037 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001038 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001039 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001040 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001041 ConvertedType = ToType;
1042 return true;
1043 }
1044 // Objective C++: We're able to convert from a pointer to an
1045 // interface to a pointer to a different interface.
1046 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1047 ConvertedType = ToType;
1048 return true;
1049 }
1050
1051 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1052 // Okay: this is some kind of implicit downcast of Objective-C
1053 // interfaces, which is permitted. However, we're going to
1054 // complain about it.
1055 IncompatibleObjC = true;
1056 ConvertedType = FromType;
1057 return true;
1058 }
Mike Stump1eb44332009-09-09 15:08:12 +00001059 }
Steve Naroff14108da2009-07-10 23:34:53 +00001060 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001061 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001062 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001063 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001064 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001065 ToPointeeType = ToBlockPtr->getPointeeType();
1066 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001067 return false;
1068
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001069 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001070 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001071 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001072 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001073 FromPointeeType = FromBlockPtr->getPointeeType();
1074 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001075 return false;
1076
Douglas Gregorc7887512008-12-19 19:13:09 +00001077 // If we have pointers to pointers, recursively check whether this
1078 // is an Objective-C conversion.
1079 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1080 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1081 IncompatibleObjC)) {
1082 // We always complain about this conversion.
1083 IncompatibleObjC = true;
1084 ConvertedType = ToType;
1085 return true;
1086 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001087 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001088 // differences in the argument and result types are in Objective-C
1089 // pointer conversions. If so, we permit the conversion (but
1090 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001091 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001092 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001093 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001094 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001095 if (FromFunctionType && ToFunctionType) {
1096 // If the function types are exactly the same, this isn't an
1097 // Objective-C pointer conversion.
1098 if (Context.getCanonicalType(FromPointeeType)
1099 == Context.getCanonicalType(ToPointeeType))
1100 return false;
1101
1102 // Perform the quick checks that will tell us whether these
1103 // function types are obviously different.
1104 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1105 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1106 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1107 return false;
1108
1109 bool HasObjCConversion = false;
1110 if (Context.getCanonicalType(FromFunctionType->getResultType())
1111 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1112 // Okay, the types match exactly. Nothing to do.
1113 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1114 ToFunctionType->getResultType(),
1115 ConvertedType, IncompatibleObjC)) {
1116 // Okay, we have an Objective-C pointer conversion.
1117 HasObjCConversion = true;
1118 } else {
1119 // Function types are too different. Abort.
1120 return false;
1121 }
Mike Stump1eb44332009-09-09 15:08:12 +00001122
Douglas Gregorc7887512008-12-19 19:13:09 +00001123 // Check argument types.
1124 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1125 ArgIdx != NumArgs; ++ArgIdx) {
1126 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1127 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1128 if (Context.getCanonicalType(FromArgType)
1129 == Context.getCanonicalType(ToArgType)) {
1130 // Okay, the types match exactly. Nothing to do.
1131 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1132 ConvertedType, IncompatibleObjC)) {
1133 // Okay, we have an Objective-C pointer conversion.
1134 HasObjCConversion = true;
1135 } else {
1136 // Argument types are too different. Abort.
1137 return false;
1138 }
1139 }
1140
1141 if (HasObjCConversion) {
1142 // We had an Objective-C conversion. Allow this pointer
1143 // conversion, but complain about it.
1144 ConvertedType = ToType;
1145 IncompatibleObjC = true;
1146 return true;
1147 }
1148 }
1149
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001150 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001151}
1152
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001153/// CheckPointerConversion - Check the pointer conversion from the
1154/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001155/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001156/// conversions for which IsPointerConversion has already returned
1157/// true. It returns true and produces a diagnostic if there was an
1158/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001159bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001160 CastExpr::CastKind &Kind,
1161 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001162 QualType FromType = From->getType();
1163
Ted Kremenek6217b802009-07-29 21:53:49 +00001164 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1165 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001166 QualType FromPointeeType = FromPtrType->getPointeeType(),
1167 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001168
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001169 if (FromPointeeType->isRecordType() &&
1170 ToPointeeType->isRecordType()) {
1171 // We must have a derived-to-base conversion. Check an
1172 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001173 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1174 From->getExprLoc(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001175 From->getSourceRange(),
1176 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001177 return true;
1178
1179 // The conversion was successful.
1180 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001181 }
1182 }
Mike Stump1eb44332009-09-09 15:08:12 +00001183 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001184 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001185 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001186 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001187 // Objective-C++ conversions are always okay.
1188 // FIXME: We should have a different class of conversions for the
1189 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001190 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001191 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001192
Steve Naroff14108da2009-07-10 23:34:53 +00001193 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001194 return false;
1195}
1196
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001197/// IsMemberPointerConversion - Determines whether the conversion of the
1198/// expression From, which has the (possibly adjusted) type FromType, can be
1199/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1200/// If so, returns true and places the converted type (that might differ from
1201/// ToType in its cv-qualifiers at some level) into ConvertedType.
1202bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001203 QualType ToType,
1204 bool InOverloadResolution,
1205 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001206 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001207 if (!ToTypePtr)
1208 return false;
1209
1210 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001211 if (From->isNullPointerConstant(Context,
1212 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1213 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001214 ConvertedType = ToType;
1215 return true;
1216 }
1217
1218 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001219 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001220 if (!FromTypePtr)
1221 return false;
1222
1223 // A pointer to member of B can be converted to a pointer to member of D,
1224 // where D is derived from B (C++ 4.11p2).
1225 QualType FromClass(FromTypePtr->getClass(), 0);
1226 QualType ToClass(ToTypePtr->getClass(), 0);
1227 // FIXME: What happens when these are dependent? Is this function even called?
1228
1229 if (IsDerivedFrom(ToClass, FromClass)) {
1230 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1231 ToClass.getTypePtr());
1232 return true;
1233 }
1234
1235 return false;
1236}
1237
1238/// CheckMemberPointerConversion - Check the member pointer conversion from the
1239/// expression From to the type ToType. This routine checks for ambiguous or
1240/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1241/// for which IsMemberPointerConversion has already returned true. It returns
1242/// true and produces a diagnostic if there was an error, or returns false
1243/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001244bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001245 CastExpr::CastKind &Kind,
1246 bool IgnoreBaseAccess) {
1247 (void)IgnoreBaseAccess;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001248 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001249 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001250 if (!FromPtrType) {
1251 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001252 assert(From->isNullPointerConstant(Context,
1253 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001254 "Expr must be null pointer constant!");
1255 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001256 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001257 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001258
Ted Kremenek6217b802009-07-29 21:53:49 +00001259 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001260 assert(ToPtrType && "No member pointer cast has a target type "
1261 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001262
Sebastian Redl21593ac2009-01-28 18:33:18 +00001263 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1264 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001265
Sebastian Redl21593ac2009-01-28 18:33:18 +00001266 // FIXME: What about dependent types?
1267 assert(FromClass->isRecordType() && "Pointer into non-class.");
1268 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001269
Douglas Gregora8f32e02009-10-06 17:59:45 +00001270 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1271 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001272 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1273 assert(DerivationOkay &&
1274 "Should not have been called if derivation isn't OK.");
1275 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001276
Sebastian Redl21593ac2009-01-28 18:33:18 +00001277 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1278 getUnqualifiedType())) {
1279 // Derivation is ambiguous. Redo the check to find the exact paths.
1280 Paths.clear();
1281 Paths.setRecordingPaths(true);
1282 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1283 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1284 (void)StillOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001285
Sebastian Redl21593ac2009-01-28 18:33:18 +00001286 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1287 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1288 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1289 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001290 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001291
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001292 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001293 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1294 << FromClass << ToClass << QualType(VBase, 0)
1295 << From->getSourceRange();
1296 return true;
1297 }
1298
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001299 // Must be a base to derived member conversion.
1300 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001301 return false;
1302}
1303
Douglas Gregor98cd5992008-10-21 23:43:52 +00001304/// IsQualificationConversion - Determines whether the conversion from
1305/// an rvalue of type FromType to ToType is a qualification conversion
1306/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001307bool
1308Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001309 FromType = Context.getCanonicalType(FromType);
1310 ToType = Context.getCanonicalType(ToType);
1311
1312 // If FromType and ToType are the same type, this is not a
1313 // qualification conversion.
1314 if (FromType == ToType)
1315 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001316
Douglas Gregor98cd5992008-10-21 23:43:52 +00001317 // (C++ 4.4p4):
1318 // A conversion can add cv-qualifiers at levels other than the first
1319 // in multi-level pointers, subject to the following rules: [...]
1320 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001321 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001322 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001323 // Within each iteration of the loop, we check the qualifiers to
1324 // determine if this still looks like a qualification
1325 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001326 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001327 // until there are no more pointers or pointers-to-members left to
1328 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001329 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001330
1331 // -- for every j > 0, if const is in cv 1,j then const is in cv
1332 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001333 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001334 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001335
Douglas Gregor98cd5992008-10-21 23:43:52 +00001336 // -- if the cv 1,j and cv 2,j are different, then const is in
1337 // every cv for 0 < k < j.
1338 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001339 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001340 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001341
Douglas Gregor98cd5992008-10-21 23:43:52 +00001342 // Keep track of whether all prior cv-qualifiers in the "to" type
1343 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001344 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001345 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001346 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001347
1348 // We are left with FromType and ToType being the pointee types
1349 // after unwrapping the original FromType and ToType the same number
1350 // of types. If we unwrapped any pointers, and if FromType and
1351 // ToType have the same unqualified type (since we checked
1352 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001353 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001354}
1355
Douglas Gregor734d9862009-01-30 23:27:23 +00001356/// Determines whether there is a user-defined conversion sequence
1357/// (C++ [over.ics.user]) that converts expression From to the type
1358/// ToType. If such a conversion exists, User will contain the
1359/// user-defined conversion sequence that performs such a conversion
1360/// and this routine will return true. Otherwise, this routine returns
1361/// false and User is unspecified.
1362///
1363/// \param AllowConversionFunctions true if the conversion should
1364/// consider conversion functions at all. If false, only constructors
1365/// will be considered.
1366///
1367/// \param AllowExplicit true if the conversion should consider C++0x
1368/// "explicit" conversion functions as well as non-explicit conversion
1369/// functions (C++0x [class.conv.fct]p2).
Sebastian Redle2b68332009-04-12 17:16:29 +00001370///
1371/// \param ForceRValue true if the expression should be treated as an rvalue
1372/// for overload resolution.
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001373/// \param UserCast true if looking for user defined conversion for a static
1374/// cast.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001375Sema::OverloadingResult Sema::IsUserDefinedConversion(
1376 Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001377 UserDefinedConversionSequence& User,
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +00001378 OverloadCandidateSet& CandidateSet,
Douglas Gregor734d9862009-01-30 23:27:23 +00001379 bool AllowConversionFunctions,
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001380 bool AllowExplicit, bool ForceRValue,
1381 bool UserCast) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001382 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00001383 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1384 // We're not going to find any constructors.
1385 } else if (CXXRecordDecl *ToRecordDecl
1386 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001387 // C++ [over.match.ctor]p1:
1388 // When objects of class type are direct-initialized (8.5), or
1389 // copy-initialized from an expression of the same or a
1390 // derived class type (8.5), overload resolution selects the
1391 // constructor. [...] For copy-initialization, the candidate
1392 // functions are all the converting constructors (12.3.1) of
1393 // that class. The argument list is the expression-list within
1394 // the parentheses of the initializer.
Douglas Gregor79b680e2009-11-13 18:44:21 +00001395 bool SuppressUserConversions = !UserCast;
1396 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1397 IsDerivedFrom(From->getType(), ToType)) {
1398 SuppressUserConversions = false;
1399 AllowConversionFunctions = false;
1400 }
1401
Mike Stump1eb44332009-09-09 15:08:12 +00001402 DeclarationName ConstructorName
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001403 = Context.DeclarationNames.getCXXConstructorName(
1404 Context.getCanonicalType(ToType).getUnqualifiedType());
1405 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump1eb44332009-09-09 15:08:12 +00001406 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001407 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001408 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00001409 // Find the constructor (which may be a template).
1410 CXXConstructorDecl *Constructor = 0;
1411 FunctionTemplateDecl *ConstructorTmpl
1412 = dyn_cast<FunctionTemplateDecl>(*Con);
1413 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001414 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001415 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1416 else
1417 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001418
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001419 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001420 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001421 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001422 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001423 1, CandidateSet,
1424 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001425 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001426 // Allow one user-defined conversion when user specifies a
1427 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregordec06662009-08-21 18:42:58 +00001428 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001429 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001430 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001431 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001432 }
1433 }
1434
Douglas Gregor734d9862009-01-30 23:27:23 +00001435 if (!AllowConversionFunctions) {
1436 // Don't allow any conversion functions to enter the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00001437 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1438 PDiag(0)
Anders Carlssonb7906612009-08-26 23:45:07 +00001439 << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001440 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001441 } else if (const RecordType *FromRecordType
Ted Kremenek6217b802009-07-29 21:53:49 +00001442 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001443 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001444 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1445 // Add all of the conversion functions as candidates.
John McCallba135432009-11-21 08:51:07 +00001446 const UnresolvedSet *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001447 = FromRecordDecl->getVisibleConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00001448 for (UnresolvedSet::iterator I = Conversions->begin(),
1449 E = Conversions->end(); I != E; ++I) {
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001450 CXXConversionDecl *Conv;
1451 FunctionTemplateDecl *ConvTemplate;
John McCallba135432009-11-21 08:51:07 +00001452 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001453 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1454 else
John McCallba135432009-11-21 08:51:07 +00001455 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001456
1457 if (AllowExplicit || !Conv->isExplicit()) {
1458 if (ConvTemplate)
1459 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1460 CandidateSet);
1461 else
1462 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1463 }
1464 }
1465 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001466 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001467
1468 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001469 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001470 case OR_Success:
1471 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001472 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001473 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1474 // C++ [over.ics.user]p1:
1475 // If the user-defined conversion is specified by a
1476 // constructor (12.3.1), the initial standard conversion
1477 // sequence converts the source type to the type required by
1478 // the argument of the constructor.
1479 //
Douglas Gregor60d62c22008-10-31 16:23:19 +00001480 QualType ThisType = Constructor->getThisType(Context);
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001481 if (Best->Conversions[0].ConversionKind ==
1482 ImplicitConversionSequence::EllipsisConversion)
1483 User.EllipsisConversion = true;
1484 else {
1485 User.Before = Best->Conversions[0].Standard;
1486 User.EllipsisConversion = false;
1487 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001488 User.ConversionFunction = Constructor;
1489 User.After.setAsIdentityConversion();
Mike Stump1eb44332009-09-09 15:08:12 +00001490 User.After.FromTypePtr
Ted Kremenek6217b802009-07-29 21:53:49 +00001491 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor60d62c22008-10-31 16:23:19 +00001492 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001493 return OR_Success;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001494 } else if (CXXConversionDecl *Conversion
1495 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1496 // C++ [over.ics.user]p1:
1497 //
1498 // [...] If the user-defined conversion is specified by a
1499 // conversion function (12.3.2), the initial standard
1500 // conversion sequence converts the source type to the
1501 // implicit object parameter of the conversion function.
1502 User.Before = Best->Conversions[0].Standard;
1503 User.ConversionFunction = Conversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001504 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001505
1506 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001507 // The second standard conversion sequence converts the
1508 // result of the user-defined conversion to the target type
1509 // for the sequence. Since an implicit conversion sequence
1510 // is an initialization, the special rules for
1511 // initialization by user-defined conversion apply when
1512 // selecting the best user-defined conversion for a
1513 // user-defined conversion sequence (see 13.3.3 and
1514 // 13.3.3.1).
1515 User.After = Best->FinalConversion;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001516 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001517 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001518 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001519 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001520 }
Mike Stump1eb44332009-09-09 15:08:12 +00001521
Douglas Gregor60d62c22008-10-31 16:23:19 +00001522 case OR_No_Viable_Function:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001523 return OR_No_Viable_Function;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001524 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001525 // No conversion here! We're done.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001526 return OR_Deleted;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001527
1528 case OR_Ambiguous:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001529 return OR_Ambiguous;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001530 }
1531
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001532 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001533}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001534
1535bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001536Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001537 ImplicitConversionSequence ICS;
1538 OverloadCandidateSet CandidateSet;
1539 OverloadingResult OvResult =
1540 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1541 CandidateSet, true, false, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001542 if (OvResult == OR_Ambiguous)
1543 Diag(From->getSourceRange().getBegin(),
1544 diag::err_typecheck_ambiguous_condition)
1545 << From->getType() << ToType << From->getSourceRange();
1546 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1547 Diag(From->getSourceRange().getBegin(),
1548 diag::err_typecheck_nonviable_condition)
1549 << From->getType() << ToType << From->getSourceRange();
1550 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001551 return false;
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001552 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001553 return true;
1554}
Douglas Gregor60d62c22008-10-31 16:23:19 +00001555
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001556/// CompareImplicitConversionSequences - Compare two implicit
1557/// conversion sequences to determine whether one is better than the
1558/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00001559ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001560Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1561 const ImplicitConversionSequence& ICS2)
1562{
1563 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1564 // conversion sequences (as defined in 13.3.3.1)
1565 // -- a standard conversion sequence (13.3.3.1.1) is a better
1566 // conversion sequence than a user-defined conversion sequence or
1567 // an ellipsis conversion sequence, and
1568 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1569 // conversion sequence than an ellipsis conversion sequence
1570 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00001571 //
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001572 if (ICS1.ConversionKind < ICS2.ConversionKind)
1573 return ImplicitConversionSequence::Better;
1574 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1575 return ImplicitConversionSequence::Worse;
1576
1577 // Two implicit conversion sequences of the same form are
1578 // indistinguishable conversion sequences unless one of the
1579 // following rules apply: (C++ 13.3.3.2p3):
1580 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1581 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump1eb44332009-09-09 15:08:12 +00001582 else if (ICS1.ConversionKind ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001583 ImplicitConversionSequence::UserDefinedConversion) {
1584 // User-defined conversion sequence U1 is a better conversion
1585 // sequence than another user-defined conversion sequence U2 if
1586 // they contain the same user-defined conversion function or
1587 // constructor and if the second standard conversion sequence of
1588 // U1 is better than the second standard conversion sequence of
1589 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001590 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001591 ICS2.UserDefined.ConversionFunction)
1592 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1593 ICS2.UserDefined.After);
1594 }
1595
1596 return ImplicitConversionSequence::Indistinguishable;
1597}
1598
1599/// CompareStandardConversionSequences - Compare two standard
1600/// conversion sequences to determine whether one is better than the
1601/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001602ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001603Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1604 const StandardConversionSequence& SCS2)
1605{
1606 // Standard conversion sequence S1 is a better conversion sequence
1607 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1608
1609 // -- S1 is a proper subsequence of S2 (comparing the conversion
1610 // sequences in the canonical form defined by 13.3.3.1.1,
1611 // excluding any Lvalue Transformation; the identity conversion
1612 // sequence is considered to be a subsequence of any
1613 // non-identity conversion sequence) or, if not that,
1614 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1615 // Neither is a proper subsequence of the other. Do nothing.
1616 ;
1617 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1618 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001619 (SCS1.Second == ICK_Identity &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001620 SCS1.Third == ICK_Identity))
1621 // SCS1 is a proper subsequence of SCS2.
1622 return ImplicitConversionSequence::Better;
1623 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1624 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001625 (SCS2.Second == ICK_Identity &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001626 SCS2.Third == ICK_Identity))
1627 // SCS2 is a proper subsequence of SCS1.
1628 return ImplicitConversionSequence::Worse;
1629
1630 // -- the rank of S1 is better than the rank of S2 (by the rules
1631 // defined below), or, if not that,
1632 ImplicitConversionRank Rank1 = SCS1.getRank();
1633 ImplicitConversionRank Rank2 = SCS2.getRank();
1634 if (Rank1 < Rank2)
1635 return ImplicitConversionSequence::Better;
1636 else if (Rank2 < Rank1)
1637 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001638
Douglas Gregor57373262008-10-22 14:17:15 +00001639 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1640 // are indistinguishable unless one of the following rules
1641 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Douglas Gregor57373262008-10-22 14:17:15 +00001643 // A conversion that is not a conversion of a pointer, or
1644 // pointer to member, to bool is better than another conversion
1645 // that is such a conversion.
1646 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1647 return SCS2.isPointerConversionToBool()
1648 ? ImplicitConversionSequence::Better
1649 : ImplicitConversionSequence::Worse;
1650
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001651 // C++ [over.ics.rank]p4b2:
1652 //
1653 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001654 // conversion of B* to A* is better than conversion of B* to
1655 // void*, and conversion of A* to void* is better than conversion
1656 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00001657 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001658 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001659 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001660 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001661 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1662 // Exactly one of the conversion sequences is a conversion to
1663 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001664 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1665 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001666 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1667 // Neither conversion sequence converts to a void pointer; compare
1668 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001669 if (ImplicitConversionSequence::CompareKind DerivedCK
1670 = CompareDerivedToBaseConversions(SCS1, SCS2))
1671 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001672 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1673 // Both conversion sequences are conversions to void
1674 // pointers. Compare the source types to determine if there's an
1675 // inheritance relationship in their sources.
1676 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1677 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1678
1679 // Adjust the types we're converting from via the array-to-pointer
1680 // conversion, if we need to.
1681 if (SCS1.First == ICK_Array_To_Pointer)
1682 FromType1 = Context.getArrayDecayedType(FromType1);
1683 if (SCS2.First == ICK_Array_To_Pointer)
1684 FromType2 = Context.getArrayDecayedType(FromType2);
1685
Mike Stump1eb44332009-09-09 15:08:12 +00001686 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001687 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001688 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001689 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001690
1691 if (IsDerivedFrom(FromPointee2, FromPointee1))
1692 return ImplicitConversionSequence::Better;
1693 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1694 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001695
1696 // Objective-C++: If one interface is more specific than the
1697 // other, it is the better one.
John McCall183700f2009-09-21 23:43:11 +00001698 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1699 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001700 if (FromIface1 && FromIface1) {
1701 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1702 return ImplicitConversionSequence::Better;
1703 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1704 return ImplicitConversionSequence::Worse;
1705 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001706 }
Douglas Gregor57373262008-10-22 14:17:15 +00001707
1708 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1709 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00001710 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001711 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001712 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001713
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001714 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001715 // C++0x [over.ics.rank]p3b4:
1716 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1717 // implicit object parameter of a non-static member function declared
1718 // without a ref-qualifier, and S1 binds an rvalue reference to an
1719 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00001720 // FIXME: We don't know if we're dealing with the implicit object parameter,
1721 // or if the member function in this case has a ref qualifier.
1722 // (Of course, we don't have ref qualifiers yet.)
1723 if (SCS1.RRefBinding != SCS2.RRefBinding)
1724 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1725 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001726
1727 // C++ [over.ics.rank]p3b4:
1728 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1729 // which the references refer are the same type except for
1730 // top-level cv-qualifiers, and the type to which the reference
1731 // initialized by S2 refers is more cv-qualified than the type
1732 // to which the reference initialized by S1 refers.
Sebastian Redla9845802009-03-29 15:27:50 +00001733 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1734 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001735 T1 = Context.getCanonicalType(T1);
1736 T2 = Context.getCanonicalType(T2);
Douglas Gregora4923eb2009-11-16 21:35:15 +00001737 if (Context.hasSameUnqualifiedType(T1, T2)) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001738 if (T2.isMoreQualifiedThan(T1))
1739 return ImplicitConversionSequence::Better;
1740 else if (T1.isMoreQualifiedThan(T2))
1741 return ImplicitConversionSequence::Worse;
1742 }
1743 }
Douglas Gregor57373262008-10-22 14:17:15 +00001744
1745 return ImplicitConversionSequence::Indistinguishable;
1746}
1747
1748/// CompareQualificationConversions - Compares two standard conversion
1749/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00001750/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1751ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00001752Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00001753 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00001754 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001755 // -- S1 and S2 differ only in their qualification conversion and
1756 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1757 // cv-qualification signature of type T1 is a proper subset of
1758 // the cv-qualification signature of type T2, and S1 is not the
1759 // deprecated string literal array-to-pointer conversion (4.2).
1760 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1761 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1762 return ImplicitConversionSequence::Indistinguishable;
1763
1764 // FIXME: the example in the standard doesn't use a qualification
1765 // conversion (!)
1766 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1767 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1768 T1 = Context.getCanonicalType(T1);
1769 T2 = Context.getCanonicalType(T2);
1770
1771 // If the types are the same, we won't learn anything by unwrapped
1772 // them.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001773 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00001774 return ImplicitConversionSequence::Indistinguishable;
1775
Mike Stump1eb44332009-09-09 15:08:12 +00001776 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00001777 = ImplicitConversionSequence::Indistinguishable;
1778 while (UnwrapSimilarPointerTypes(T1, T2)) {
1779 // Within each iteration of the loop, we check the qualifiers to
1780 // determine if this still looks like a qualification
1781 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001782 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001783 // until there are no more pointers or pointers-to-members left
1784 // to unwrap. This essentially mimics what
1785 // IsQualificationConversion does, but here we're checking for a
1786 // strict subset of qualifiers.
1787 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1788 // The qualifiers are the same, so this doesn't tell us anything
1789 // about how the sequences rank.
1790 ;
1791 else if (T2.isMoreQualifiedThan(T1)) {
1792 // T1 has fewer qualifiers, so it could be the better sequence.
1793 if (Result == ImplicitConversionSequence::Worse)
1794 // Neither has qualifiers that are a subset of the other's
1795 // qualifiers.
1796 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001797
Douglas Gregor57373262008-10-22 14:17:15 +00001798 Result = ImplicitConversionSequence::Better;
1799 } else if (T1.isMoreQualifiedThan(T2)) {
1800 // T2 has fewer qualifiers, so it could be the better sequence.
1801 if (Result == ImplicitConversionSequence::Better)
1802 // Neither has qualifiers that are a subset of the other's
1803 // qualifiers.
1804 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001805
Douglas Gregor57373262008-10-22 14:17:15 +00001806 Result = ImplicitConversionSequence::Worse;
1807 } else {
1808 // Qualifiers are disjoint.
1809 return ImplicitConversionSequence::Indistinguishable;
1810 }
1811
1812 // If the types after this point are equivalent, we're done.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001813 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00001814 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001815 }
1816
Douglas Gregor57373262008-10-22 14:17:15 +00001817 // Check that the winning standard conversion sequence isn't using
1818 // the deprecated string literal array to pointer conversion.
1819 switch (Result) {
1820 case ImplicitConversionSequence::Better:
1821 if (SCS1.Deprecated)
1822 Result = ImplicitConversionSequence::Indistinguishable;
1823 break;
1824
1825 case ImplicitConversionSequence::Indistinguishable:
1826 break;
1827
1828 case ImplicitConversionSequence::Worse:
1829 if (SCS2.Deprecated)
1830 Result = ImplicitConversionSequence::Indistinguishable;
1831 break;
1832 }
1833
1834 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001835}
1836
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001837/// CompareDerivedToBaseConversions - Compares two standard conversion
1838/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001839/// various kinds of derived-to-base conversions (C++
1840/// [over.ics.rank]p4b3). As part of these checks, we also look at
1841/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001842ImplicitConversionSequence::CompareKind
1843Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1844 const StandardConversionSequence& SCS2) {
1845 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1846 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1847 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1848 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1849
1850 // Adjust the types we're converting from via the array-to-pointer
1851 // conversion, if we need to.
1852 if (SCS1.First == ICK_Array_To_Pointer)
1853 FromType1 = Context.getArrayDecayedType(FromType1);
1854 if (SCS2.First == ICK_Array_To_Pointer)
1855 FromType2 = Context.getArrayDecayedType(FromType2);
1856
1857 // Canonicalize all of the types.
1858 FromType1 = Context.getCanonicalType(FromType1);
1859 ToType1 = Context.getCanonicalType(ToType1);
1860 FromType2 = Context.getCanonicalType(FromType2);
1861 ToType2 = Context.getCanonicalType(ToType2);
1862
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001863 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001864 //
1865 // If class B is derived directly or indirectly from class A and
1866 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001867 //
1868 // For Objective-C, we let A, B, and C also be Objective-C
1869 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001870
1871 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00001872 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001873 SCS2.Second == ICK_Pointer_Conversion &&
1874 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1875 FromType1->isPointerType() && FromType2->isPointerType() &&
1876 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001877 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001878 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00001879 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001880 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001881 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001882 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001883 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001884 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001885
John McCall183700f2009-09-21 23:43:11 +00001886 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1887 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1888 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1889 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001890
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001891 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001892 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1893 if (IsDerivedFrom(ToPointee1, ToPointee2))
1894 return ImplicitConversionSequence::Better;
1895 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1896 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001897
1898 if (ToIface1 && ToIface2) {
1899 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1900 return ImplicitConversionSequence::Better;
1901 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1902 return ImplicitConversionSequence::Worse;
1903 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001904 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001905
1906 // -- conversion of B* to A* is better than conversion of C* to A*,
1907 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1908 if (IsDerivedFrom(FromPointee2, FromPointee1))
1909 return ImplicitConversionSequence::Better;
1910 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1911 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00001912
Douglas Gregorcb7de522008-11-26 23:31:11 +00001913 if (FromIface1 && FromIface2) {
1914 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1915 return ImplicitConversionSequence::Better;
1916 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1917 return ImplicitConversionSequence::Worse;
1918 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001919 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001920 }
1921
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001922 // Compare based on reference bindings.
1923 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1924 SCS1.Second == ICK_Derived_To_Base) {
1925 // -- binding of an expression of type C to a reference of type
1926 // B& is better than binding an expression of type C to a
1927 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00001928 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1929 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001930 if (IsDerivedFrom(ToType1, ToType2))
1931 return ImplicitConversionSequence::Better;
1932 else if (IsDerivedFrom(ToType2, ToType1))
1933 return ImplicitConversionSequence::Worse;
1934 }
1935
Douglas Gregor225c41e2008-11-03 19:09:14 +00001936 // -- binding of an expression of type B to a reference of type
1937 // A& is better than binding an expression of type C to a
1938 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00001939 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1940 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001941 if (IsDerivedFrom(FromType2, FromType1))
1942 return ImplicitConversionSequence::Better;
1943 else if (IsDerivedFrom(FromType1, FromType2))
1944 return ImplicitConversionSequence::Worse;
1945 }
1946 }
Fariborz Jahanian2357da02009-10-20 20:07:35 +00001947
1948 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00001949 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
1950 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
1951 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
1952 const MemberPointerType * FromMemPointer1 =
1953 FromType1->getAs<MemberPointerType>();
1954 const MemberPointerType * ToMemPointer1 =
1955 ToType1->getAs<MemberPointerType>();
1956 const MemberPointerType * FromMemPointer2 =
1957 FromType2->getAs<MemberPointerType>();
1958 const MemberPointerType * ToMemPointer2 =
1959 ToType2->getAs<MemberPointerType>();
1960 const Type *FromPointeeType1 = FromMemPointer1->getClass();
1961 const Type *ToPointeeType1 = ToMemPointer1->getClass();
1962 const Type *FromPointeeType2 = FromMemPointer2->getClass();
1963 const Type *ToPointeeType2 = ToMemPointer2->getClass();
1964 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
1965 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
1966 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
1967 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00001968 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00001969 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1970 if (IsDerivedFrom(ToPointee1, ToPointee2))
1971 return ImplicitConversionSequence::Worse;
1972 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1973 return ImplicitConversionSequence::Better;
1974 }
1975 // conversion of B::* to C::* is better than conversion of A::* to C::*
1976 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
1977 if (IsDerivedFrom(FromPointee1, FromPointee2))
1978 return ImplicitConversionSequence::Better;
1979 else if (IsDerivedFrom(FromPointee2, FromPointee1))
1980 return ImplicitConversionSequence::Worse;
1981 }
1982 }
1983
Douglas Gregor225c41e2008-11-03 19:09:14 +00001984 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1985 SCS1.Second == ICK_Derived_To_Base) {
1986 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregora4923eb2009-11-16 21:35:15 +00001987 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1988 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00001989 if (IsDerivedFrom(ToType1, ToType2))
1990 return ImplicitConversionSequence::Better;
1991 else if (IsDerivedFrom(ToType2, ToType1))
1992 return ImplicitConversionSequence::Worse;
1993 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001994
Douglas Gregor225c41e2008-11-03 19:09:14 +00001995 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001996 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1997 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00001998 if (IsDerivedFrom(FromType2, FromType1))
1999 return ImplicitConversionSequence::Better;
2000 else if (IsDerivedFrom(FromType1, FromType2))
2001 return ImplicitConversionSequence::Worse;
2002 }
2003 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002004
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002005 return ImplicitConversionSequence::Indistinguishable;
2006}
2007
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002008/// TryCopyInitialization - Try to copy-initialize a value of type
2009/// ToType from the expression From. Return the implicit conversion
2010/// sequence required to pass this argument, which may be a bad
2011/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00002012/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redle2b68332009-04-12 17:16:29 +00002013/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2014/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00002015ImplicitConversionSequence
2016Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002017 bool SuppressUserConversions, bool ForceRValue,
2018 bool InOverloadResolution) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00002019 if (ToType->isReferenceType()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002020 ImplicitConversionSequence ICS;
Mike Stump1eb44332009-09-09 15:08:12 +00002021 CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00002022 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002023 SuppressUserConversions,
2024 /*AllowExplicit=*/false,
2025 ForceRValue,
2026 &ICS);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002027 return ICS;
2028 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002029 return TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002030 SuppressUserConversions,
2031 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002032 ForceRValue,
2033 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002034 }
2035}
2036
Sebastian Redle2b68332009-04-12 17:16:29 +00002037/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2038/// the expression @p From. Returns true (and emits a diagnostic) if there was
2039/// an error, returns false if the initialization succeeded. Elidable should
2040/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2041/// differently in C++0x for this case.
Mike Stump1eb44332009-09-09 15:08:12 +00002042bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +00002043 const char* Flavor, bool Elidable) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002044 if (!getLangOptions().CPlusPlus) {
2045 // In C, argument passing is the same as performing an assignment.
2046 QualType FromType = From->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002047
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002048 AssignConvertType ConvTy =
2049 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00002050 if (ConvTy != Compatible &&
2051 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2052 ConvTy = Compatible;
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002054 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2055 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002056 }
Sebastian Redle2b68332009-04-12 17:16:29 +00002057
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002058 if (ToType->isReferenceType())
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002059 return CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00002060 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002061 /*SuppressUserConversions=*/false,
2062 /*AllowExplicit=*/false,
2063 /*ForceRValue=*/false);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002064
Sebastian Redle2b68332009-04-12 17:16:29 +00002065 if (!PerformImplicitConversion(From, ToType, Flavor,
2066 /*AllowExplicit=*/false, Elidable))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002067 return false;
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002068 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian455acd92009-09-22 19:53:15 +00002069 return Diag(From->getSourceRange().getBegin(),
2070 diag::err_typecheck_convert_incompatible)
2071 << ToType << From->getType() << Flavor << From->getSourceRange();
Fariborz Jahanian455acd92009-09-22 19:53:15 +00002072 return true;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002073}
2074
Douglas Gregor96176b32008-11-18 23:14:02 +00002075/// TryObjectArgumentInitialization - Try to initialize the object
2076/// parameter of the given member function (@c Method) from the
2077/// expression @p From.
2078ImplicitConversionSequence
2079Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
2080 QualType ClassType = Context.getTypeDeclType(Method->getParent());
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002081 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2082 // const volatile object.
2083 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2084 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2085 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00002086
2087 // Set up the conversion sequence as a "bad" conversion, to allow us
2088 // to exit early.
2089 ImplicitConversionSequence ICS;
2090 ICS.Standard.setAsIdentityConversion();
2091 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2092
2093 // We need to have an object of class type.
2094 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002095 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00002096 FromType = PT->getPointeeType();
2097
2098 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002099
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002100 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00002101 // where X is the class of which the function is a member
2102 // (C++ [over.match.funcs]p4). However, when finding an implicit
2103 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00002104 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00002105 // (C++ [over.match.funcs]p5). We perform a simplified version of
2106 // reference binding here, that allows class rvalues to bind to
2107 // non-constant references.
2108
2109 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2110 // with the implicit object parameter (C++ [over.match.funcs]p5).
2111 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002112 if (ImplicitParamType.getCVRQualifiers()
2113 != FromTypeCanon.getLocalCVRQualifiers() &&
Douglas Gregorb1c2ea52009-11-05 00:07:36 +00002114 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon))
Douglas Gregor96176b32008-11-18 23:14:02 +00002115 return ICS;
2116
2117 // Check that we have either the same type or a derived type. It
2118 // affects the conversion rank.
2119 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002120 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor96176b32008-11-18 23:14:02 +00002121 ICS.Standard.Second = ICK_Identity;
2122 else if (IsDerivedFrom(FromType, ClassType))
2123 ICS.Standard.Second = ICK_Derived_To_Base;
2124 else
2125 return ICS;
2126
2127 // Success. Mark this as a reference binding.
2128 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2129 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2130 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2131 ICS.Standard.ReferenceBinding = true;
2132 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00002133 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002134 return ICS;
2135}
2136
2137/// PerformObjectArgumentInitialization - Perform initialization of
2138/// the implicit object parameter for the given Method with the given
2139/// expression.
2140bool
2141Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002142 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00002143 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00002144 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002145
Ted Kremenek6217b802009-07-29 21:53:49 +00002146 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002147 FromRecordType = PT->getPointeeType();
2148 DestType = Method->getThisType(Context);
2149 } else {
2150 FromRecordType = From->getType();
2151 DestType = ImplicitParamRecordType;
2152 }
2153
Mike Stump1eb44332009-09-09 15:08:12 +00002154 ImplicitConversionSequence ICS
Douglas Gregor96176b32008-11-18 23:14:02 +00002155 = TryObjectArgumentInitialization(From, Method);
2156 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2157 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002158 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00002159 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002160
Douglas Gregor96176b32008-11-18 23:14:02 +00002161 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssona552f7c2009-05-01 18:34:30 +00002162 CheckDerivedToBaseConversion(FromRecordType,
2163 ImplicitParamRecordType,
Douglas Gregor96176b32008-11-18 23:14:02 +00002164 From->getSourceRange().getBegin(),
2165 From->getSourceRange()))
2166 return true;
2167
Mike Stump1eb44332009-09-09 15:08:12 +00002168 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson116b7d92009-08-07 18:45:49 +00002169 /*isLvalue=*/true);
Douglas Gregor96176b32008-11-18 23:14:02 +00002170 return false;
2171}
2172
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002173/// TryContextuallyConvertToBool - Attempt to contextually convert the
2174/// expression From to bool (C++0x [conv]p3).
2175ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump1eb44332009-09-09 15:08:12 +00002176 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002177 // FIXME: Are these flags correct?
2178 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00002179 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00002180 /*ForceRValue=*/false,
2181 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002182}
2183
2184/// PerformContextuallyConvertToBool - Perform a contextual conversion
2185/// of the expression From to bool (C++0x [conv]p3).
2186bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2187 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2188 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2189 return false;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002190
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002191 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002192 return Diag(From->getSourceRange().getBegin(),
2193 diag::err_typecheck_bool_condition)
2194 << From->getType() << From->getSourceRange();
2195 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002196}
2197
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002198/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00002199/// candidate functions, using the given function call arguments. If
2200/// @p SuppressUserConversions, then don't allow user-defined
2201/// conversions via constructors or conversion operators.
Sebastian Redle2b68332009-04-12 17:16:29 +00002202/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2203/// hacky way to implement the overloading rules for elidable copy
2204/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002205///
2206/// \para PartialOverloading true if we are performing "partial" overloading
2207/// based on an incomplete set of function arguments. This feature is used by
2208/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00002209void
2210Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002211 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002212 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00002213 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002214 bool ForceRValue,
2215 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00002216 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002217 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002218 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00002219 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002220 "Use AddConversionCandidate for conversion functions");
Mike Stump1eb44332009-09-09 15:08:12 +00002221 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00002222 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00002223
Douglas Gregor88a35142008-12-22 05:46:06 +00002224 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002225 if (!isa<CXXConstructorDecl>(Method)) {
2226 // If we get here, it's because we're calling a member function
2227 // that is named without a member access expression (e.g.,
2228 // "this->f") that was either written explicitly or created
2229 // implicitly. This can happen with a qualified call to a member
2230 // function, e.g., X::f(). We use a NULL object as the implied
2231 // object argument (C++ [over.call.func]p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002232 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002233 SuppressUserConversions, ForceRValue);
2234 return;
2235 }
2236 // We treat a constructor like a non-member function, since its object
2237 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00002238 }
2239
Douglas Gregorfd476482009-11-13 23:59:09 +00002240 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00002241 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00002242
2243 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2244 // C++ [class.copy]p3:
2245 // A member function template is never instantiated to perform the copy
2246 // of a class object to an object of its class type.
2247 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2248 if (NumArgs == 1 &&
2249 Constructor->isCopyConstructorLikeSpecialization() &&
2250 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2251 return;
2252 }
2253
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002254 // Add this candidate
2255 CandidateSet.push_back(OverloadCandidate());
2256 OverloadCandidate& Candidate = CandidateSet.back();
2257 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00002258 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002259 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002260 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +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).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00002267 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2268 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002269 Candidate.Viable = false;
2270 return;
2271 }
2272
2273 // (C++ 13.3.2p2): A candidate function having more than m parameters
2274 // is viable only if the (m+1)st parameter has a default argument
2275 // (8.3.6). For the purposes of overload resolution, the
2276 // parameter list is truncated on the right, so that there are
2277 // exactly m parameters.
2278 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002279 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002280 // Not enough arguments.
2281 Candidate.Viable = false;
2282 return;
2283 }
2284
2285 // Determine the implicit conversion sequences for each of the
2286 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002287 Candidate.Conversions.resize(NumArgs);
2288 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2289 if (ArgIdx < NumArgsInProto) {
2290 // (C++ 13.3.2p3): for F to be a viable function, there shall
2291 // exist for each argument an implicit conversion sequence
2292 // (13.3.3.1) that converts that argument to the corresponding
2293 // parameter of F.
2294 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002295 Candidate.Conversions[ArgIdx]
2296 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002297 SuppressUserConversions, ForceRValue,
2298 /*InOverloadResolution=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00002299 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002300 == ImplicitConversionSequence::BadConversion) {
Fariborz Jahanian99d6c442009-09-28 19:06:58 +00002301 // 13.3.3.1-p10 If several different sequences of conversions exist that
2302 // each convert the argument to the parameter type, the implicit conversion
2303 // sequence associated with the parameter is defined to be the unique conversion
2304 // sequence designated the ambiguous conversion sequence. For the purpose of
2305 // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2306 // conversion sequence is treated as a user-defined sequence that is
2307 // indistinguishable from any other user-defined conversion sequence
Fariborz Jahanian4a6a2b82009-09-29 17:31:54 +00002308 if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
Fariborz Jahanian99d6c442009-09-28 19:06:58 +00002309 Candidate.Conversions[ArgIdx].ConversionKind =
2310 ImplicitConversionSequence::UserDefinedConversion;
Fariborz Jahanian4a6a2b82009-09-29 17:31:54 +00002311 // Set the conversion function to one of them. As due to ambiguity,
2312 // they carry the same weight and is needed for overload resolution
2313 // later.
2314 Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2315 Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2316 }
Fariborz Jahanian99d6c442009-09-28 19:06:58 +00002317 else {
2318 Candidate.Viable = false;
2319 break;
2320 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002321 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002322 } else {
2323 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2324 // argument for which there is no corresponding parameter is
2325 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002326 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002327 = ImplicitConversionSequence::EllipsisConversion;
2328 }
2329 }
2330}
2331
Douglas Gregor063daf62009-03-13 18:40:31 +00002332/// \brief Add all of the function declarations in the given function set to
2333/// the overload canddiate set.
2334void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2335 Expr **Args, unsigned NumArgs,
2336 OverloadCandidateSet& CandidateSet,
2337 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00002338 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor063daf62009-03-13 18:40:31 +00002339 FEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00002340 F != FEnd; ++F) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002341 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2342 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2343 AddMethodCandidate(cast<CXXMethodDecl>(FD),
2344 Args[0], Args + 1, NumArgs - 1,
2345 CandidateSet, SuppressUserConversions);
2346 else
2347 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2348 SuppressUserConversions);
2349 } else {
2350 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2351 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2352 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2353 AddMethodTemplateCandidate(FunTmpl,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002354 /*FIXME: explicit args */false, 0, 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00002355 Args[0], Args + 1, NumArgs - 1,
2356 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00002357 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00002358 else
2359 AddTemplateOverloadCandidate(FunTmpl,
2360 /*FIXME: explicit args */false, 0, 0,
2361 Args, NumArgs, CandidateSet,
2362 SuppressUserConversions);
2363 }
Douglas Gregor364e0212009-06-27 21:05:07 +00002364 }
Douglas Gregor063daf62009-03-13 18:40:31 +00002365}
2366
John McCall314be4e2009-11-17 07:50:12 +00002367/// AddMethodCandidate - Adds a named decl (which is some kind of
2368/// method) as a method candidate to the given overload set.
2369void Sema::AddMethodCandidate(NamedDecl *Decl, Expr *Object,
2370 Expr **Args, unsigned NumArgs,
2371 OverloadCandidateSet& CandidateSet,
2372 bool SuppressUserConversions, bool ForceRValue) {
2373
2374 // FIXME: use this
2375 //DeclContext *ActingContext = Decl->getDeclContext();
2376
2377 if (isa<UsingShadowDecl>(Decl))
2378 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2379
2380 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2381 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2382 "Expected a member function template");
2383 AddMethodTemplateCandidate(TD, false, 0, 0,
2384 Object, Args, NumArgs,
2385 CandidateSet,
2386 SuppressUserConversions,
2387 ForceRValue);
2388 } else {
2389 AddMethodCandidate(cast<CXXMethodDecl>(Decl), Object, Args, NumArgs,
2390 CandidateSet, SuppressUserConversions, ForceRValue);
2391 }
2392}
2393
Douglas Gregor96176b32008-11-18 23:14:02 +00002394/// AddMethodCandidate - Adds the given C++ member function to the set
2395/// of candidate functions, using the given function call arguments
2396/// and the object argument (@c Object). For example, in a call
2397/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2398/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2399/// allow user-defined conversions via constructors or conversion
Sebastian Redle2b68332009-04-12 17:16:29 +00002400/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2401/// a slightly hacky way to implement the overloading rules for elidable copy
2402/// initialization in C++0x (C++0x 12.8p15).
Mike Stump1eb44332009-09-09 15:08:12 +00002403void
Douglas Gregor96176b32008-11-18 23:14:02 +00002404Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2405 Expr **Args, unsigned NumArgs,
2406 OverloadCandidateSet& CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00002407 bool SuppressUserConversions, bool ForceRValue) {
2408 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002409 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00002410 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002411 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor96176b32008-11-18 23:14:02 +00002412 "Use AddConversionCandidate for conversion functions");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002413 assert(!isa<CXXConstructorDecl>(Method) &&
2414 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00002415
Douglas Gregor3f396022009-09-28 04:47:19 +00002416 if (!CandidateSet.isNewCandidate(Method))
2417 return;
2418
Douglas Gregor96176b32008-11-18 23:14:02 +00002419 // Add this candidate
2420 CandidateSet.push_back(OverloadCandidate());
2421 OverloadCandidate& Candidate = CandidateSet.back();
2422 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002423 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002424 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002425
2426 unsigned NumArgsInProto = Proto->getNumArgs();
2427
2428 // (C++ 13.3.2p2): A candidate function having fewer than m
2429 // parameters is viable only if it has an ellipsis in its parameter
2430 // list (8.3.5).
2431 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2432 Candidate.Viable = false;
2433 return;
2434 }
2435
2436 // (C++ 13.3.2p2): A candidate function having more than m parameters
2437 // is viable only if the (m+1)st parameter has a default argument
2438 // (8.3.6). For the purposes of overload resolution, the
2439 // parameter list is truncated on the right, so that there are
2440 // exactly m parameters.
2441 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2442 if (NumArgs < MinRequiredArgs) {
2443 // Not enough arguments.
2444 Candidate.Viable = false;
2445 return;
2446 }
2447
2448 Candidate.Viable = true;
2449 Candidate.Conversions.resize(NumArgs + 1);
2450
Douglas Gregor88a35142008-12-22 05:46:06 +00002451 if (Method->isStatic() || !Object)
2452 // The implicit object argument is ignored.
2453 Candidate.IgnoreObjectArgument = true;
2454 else {
2455 // Determine the implicit conversion sequence for the object
2456 // parameter.
2457 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
Mike Stump1eb44332009-09-09 15:08:12 +00002458 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor88a35142008-12-22 05:46:06 +00002459 == ImplicitConversionSequence::BadConversion) {
2460 Candidate.Viable = false;
2461 return;
2462 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002463 }
2464
2465 // Determine the implicit conversion sequences for each of the
2466 // arguments.
2467 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2468 if (ArgIdx < NumArgsInProto) {
2469 // (C++ 13.3.2p3): for F to be a viable function, there shall
2470 // exist for each argument an implicit conversion sequence
2471 // (13.3.3.1) that converts that argument to the corresponding
2472 // parameter of F.
2473 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002474 Candidate.Conversions[ArgIdx + 1]
2475 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002476 SuppressUserConversions, ForceRValue,
Anders Carlsson08972922009-08-28 15:33:32 +00002477 /*InOverloadResolution=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00002478 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002479 == ImplicitConversionSequence::BadConversion) {
2480 Candidate.Viable = false;
2481 break;
2482 }
2483 } else {
2484 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2485 // argument for which there is no corresponding parameter is
2486 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002487 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002488 = ImplicitConversionSequence::EllipsisConversion;
2489 }
2490 }
2491}
2492
Douglas Gregor6b906862009-08-21 00:16:32 +00002493/// \brief Add a C++ member function template as a candidate to the candidate
2494/// set, using template argument deduction to produce an appropriate member
2495/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002496void
Douglas Gregor6b906862009-08-21 00:16:32 +00002497Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2498 bool HasExplicitTemplateArgs,
John McCall833ca992009-10-29 08:12:44 +00002499 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002500 unsigned NumExplicitTemplateArgs,
2501 Expr *Object, Expr **Args, unsigned NumArgs,
2502 OverloadCandidateSet& CandidateSet,
2503 bool SuppressUserConversions,
2504 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002505 if (!CandidateSet.isNewCandidate(MethodTmpl))
2506 return;
2507
Douglas Gregor6b906862009-08-21 00:16:32 +00002508 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002509 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00002510 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002511 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00002512 // candidate functions in the usual way.113) A given name can refer to one
2513 // or more function templates and also to a set of overloaded non-template
2514 // functions. In such a case, the candidate functions generated from each
2515 // function template are combined with the set of non-template candidate
2516 // functions.
2517 TemplateDeductionInfo Info(Context);
2518 FunctionDecl *Specialization = 0;
2519 if (TemplateDeductionResult Result
2520 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2521 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2522 Args, NumArgs, Specialization, Info)) {
2523 // FIXME: Record what happened with template argument deduction, so
2524 // that we can give the user a beautiful diagnostic.
2525 (void)Result;
2526 return;
2527 }
Mike Stump1eb44332009-09-09 15:08:12 +00002528
Douglas Gregor6b906862009-08-21 00:16:32 +00002529 // Add the function template specialization produced by template argument
2530 // deduction as a candidate.
2531 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00002532 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00002533 "Specialization is not a member function?");
Mike Stump1eb44332009-09-09 15:08:12 +00002534 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002535 CandidateSet, SuppressUserConversions, ForceRValue);
2536}
2537
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002538/// \brief Add a C++ function template specialization as a candidate
2539/// in the candidate set, using template argument deduction to produce
2540/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002541void
Douglas Gregore53060f2009-06-25 22:08:12 +00002542Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002543 bool HasExplicitTemplateArgs,
John McCall833ca992009-10-29 08:12:44 +00002544 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002545 unsigned NumExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002546 Expr **Args, unsigned NumArgs,
2547 OverloadCandidateSet& CandidateSet,
2548 bool SuppressUserConversions,
2549 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002550 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2551 return;
2552
Douglas Gregore53060f2009-06-25 22:08:12 +00002553 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002554 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00002555 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002556 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00002557 // candidate functions in the usual way.113) A given name can refer to one
2558 // or more function templates and also to a set of overloaded non-template
2559 // functions. In such a case, the candidate functions generated from each
2560 // function template are combined with the set of non-template candidate
2561 // functions.
2562 TemplateDeductionInfo Info(Context);
2563 FunctionDecl *Specialization = 0;
2564 if (TemplateDeductionResult Result
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002565 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2566 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2567 Args, NumArgs, Specialization, Info)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002568 // FIXME: Record what happened with template argument deduction, so
2569 // that we can give the user a beautiful diagnostic.
2570 (void)Result;
2571 return;
2572 }
Mike Stump1eb44332009-09-09 15:08:12 +00002573
Douglas Gregore53060f2009-06-25 22:08:12 +00002574 // Add the function template specialization produced by template argument
2575 // deduction as a candidate.
2576 assert(Specialization && "Missing function template specialization?");
2577 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2578 SuppressUserConversions, ForceRValue);
2579}
Mike Stump1eb44332009-09-09 15:08:12 +00002580
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002581/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00002582/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002583/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00002584/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002585/// (which may or may not be the same type as the type that the
2586/// conversion function produces).
2587void
2588Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2589 Expr *From, QualType ToType,
2590 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002591 assert(!Conversion->getDescribedFunctionTemplate() &&
2592 "Conversion function templates use AddTemplateConversionCandidate");
2593
Douglas Gregor3f396022009-09-28 04:47:19 +00002594 if (!CandidateSet.isNewCandidate(Conversion))
2595 return;
2596
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002597 // Add this candidate
2598 CandidateSet.push_back(OverloadCandidate());
2599 OverloadCandidate& Candidate = CandidateSet.back();
2600 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002601 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002602 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002603 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump1eb44332009-09-09 15:08:12 +00002604 Candidate.FinalConversion.FromTypePtr
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002605 = Conversion->getConversionType().getAsOpaquePtr();
2606 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2607
Douglas Gregor96176b32008-11-18 23:14:02 +00002608 // Determine the implicit conversion sequence for the implicit
2609 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002610 Candidate.Viable = true;
2611 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00002612 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002613 // Conversion functions to a different type in the base class is visible in
2614 // the derived class. So, a derived to base conversion should not participate
2615 // in overload resolution.
2616 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2617 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump1eb44332009-09-09 15:08:12 +00002618 if (Candidate.Conversions[0].ConversionKind
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002619 == ImplicitConversionSequence::BadConversion) {
2620 Candidate.Viable = false;
2621 return;
2622 }
Fariborz Jahanian3759a032009-10-19 19:18:20 +00002623
2624 // We won't go through a user-define type conversion function to convert a
2625 // derived to base as such conversions are given Conversion Rank. They only
2626 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2627 QualType FromCanon
2628 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2629 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2630 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2631 Candidate.Viable = false;
2632 return;
2633 }
2634
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002635
2636 // To determine what the conversion from the result of calling the
2637 // conversion function to the type we're eventually trying to
2638 // convert to (ToType), we need to synthesize a call to the
2639 // conversion function and attempt copy initialization from it. This
2640 // makes sure that we get the right semantics with respect to
2641 // lvalues/rvalues and the type. Fortunately, we can allocate this
2642 // call on the stack and we don't need its arguments to be
2643 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00002644 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002645 From->getLocStart());
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002646 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman73c39ab2009-10-20 08:27:19 +00002647 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002648 &ConversionRef, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002649
2650 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00002651 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2652 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00002653 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002654 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002655 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00002656 ImplicitConversionSequence ICS =
2657 TryCopyInitialization(&Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002658 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002659 /*ForceRValue=*/false,
2660 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002661
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002662 switch (ICS.ConversionKind) {
2663 case ImplicitConversionSequence::StandardConversion:
2664 Candidate.FinalConversion = ICS.Standard;
2665 break;
2666
2667 case ImplicitConversionSequence::BadConversion:
2668 Candidate.Viable = false;
2669 break;
2670
2671 default:
Mike Stump1eb44332009-09-09 15:08:12 +00002672 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002673 "Can only end up with a standard conversion sequence or failure");
2674 }
2675}
2676
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002677/// \brief Adds a conversion function template specialization
2678/// candidate to the overload set, using template argument deduction
2679/// to deduce the template arguments of the conversion function
2680/// template from the type that we are converting to (C++
2681/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00002682void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002683Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2684 Expr *From, QualType ToType,
2685 OverloadCandidateSet &CandidateSet) {
2686 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2687 "Only conversion function templates permitted here");
2688
Douglas Gregor3f396022009-09-28 04:47:19 +00002689 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2690 return;
2691
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002692 TemplateDeductionInfo Info(Context);
2693 CXXConversionDecl *Specialization = 0;
2694 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00002695 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002696 Specialization, Info)) {
2697 // FIXME: Record what happened with template argument deduction, so
2698 // that we can give the user a beautiful diagnostic.
2699 (void)Result;
2700 return;
2701 }
Mike Stump1eb44332009-09-09 15:08:12 +00002702
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002703 // Add the conversion function template specialization produced by
2704 // template argument deduction as a candidate.
2705 assert(Specialization && "Missing function template specialization?");
2706 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2707}
2708
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002709/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2710/// converts the given @c Object to a function pointer via the
2711/// conversion function @c Conversion, and then attempts to call it
2712/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2713/// the type of function that we'll eventually be calling.
2714void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor72564e72009-02-26 23:50:07 +00002715 const FunctionProtoType *Proto,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002716 Expr *Object, Expr **Args, unsigned NumArgs,
2717 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002718 if (!CandidateSet.isNewCandidate(Conversion))
2719 return;
2720
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002721 CandidateSet.push_back(OverloadCandidate());
2722 OverloadCandidate& Candidate = CandidateSet.back();
2723 Candidate.Function = 0;
2724 Candidate.Surrogate = Conversion;
2725 Candidate.Viable = true;
2726 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002727 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002728 Candidate.Conversions.resize(NumArgs + 1);
2729
2730 // Determine the implicit conversion sequence for the implicit
2731 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00002732 ImplicitConversionSequence ObjectInit
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002733 = TryObjectArgumentInitialization(Object, Conversion);
2734 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2735 Candidate.Viable = false;
2736 return;
2737 }
2738
2739 // The first conversion is actually a user-defined conversion whose
2740 // first conversion is ObjectInit's standard conversion (which is
2741 // effectively a reference binding). Record it as such.
Mike Stump1eb44332009-09-09 15:08:12 +00002742 Candidate.Conversions[0].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002743 = ImplicitConversionSequence::UserDefinedConversion;
2744 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002745 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002746 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00002747 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002748 = Candidate.Conversions[0].UserDefined.Before;
2749 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2750
Mike Stump1eb44332009-09-09 15:08:12 +00002751 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002752 unsigned NumArgsInProto = Proto->getNumArgs();
2753
2754 // (C++ 13.3.2p2): A candidate function having fewer than m
2755 // parameters is viable only if it has an ellipsis in its parameter
2756 // list (8.3.5).
2757 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2758 Candidate.Viable = false;
2759 return;
2760 }
2761
2762 // Function types don't have any default arguments, so just check if
2763 // we have enough arguments.
2764 if (NumArgs < NumArgsInProto) {
2765 // Not enough arguments.
2766 Candidate.Viable = false;
2767 return;
2768 }
2769
2770 // Determine the implicit conversion sequences for each of the
2771 // arguments.
2772 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2773 if (ArgIdx < NumArgsInProto) {
2774 // (C++ 13.3.2p3): for F to be a viable function, there shall
2775 // exist for each argument an implicit conversion sequence
2776 // (13.3.3.1) that converts that argument to the corresponding
2777 // parameter of F.
2778 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002779 Candidate.Conversions[ArgIdx + 1]
2780 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002781 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002782 /*ForceRValue=*/false,
2783 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002784 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002785 == ImplicitConversionSequence::BadConversion) {
2786 Candidate.Viable = false;
2787 break;
2788 }
2789 } else {
2790 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2791 // argument for which there is no corresponding parameter is
2792 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002793 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002794 = ImplicitConversionSequence::EllipsisConversion;
2795 }
2796 }
2797}
2798
Mike Stump390b4cc2009-05-16 07:39:55 +00002799// FIXME: This will eventually be removed, once we've migrated all of the
2800// operator overloading logic over to the scheme used by binary operators, which
2801// works for template instantiation.
Douglas Gregor063daf62009-03-13 18:40:31 +00002802void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002803 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00002804 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002805 OverloadCandidateSet& CandidateSet,
2806 SourceRange OpRange) {
Douglas Gregor063daf62009-03-13 18:40:31 +00002807 FunctionSet Functions;
2808
2809 QualType T1 = Args[0]->getType();
2810 QualType T2;
2811 if (NumArgs > 1)
2812 T2 = Args[1]->getType();
2813
2814 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002815 if (S)
2816 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redl644be852009-10-23 19:23:15 +00002817 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00002818 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2819 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002820 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00002821}
2822
2823/// \brief Add overload candidates for overloaded operators that are
2824/// member functions.
2825///
2826/// Add the overloaded operator candidates that are member functions
2827/// for the operator Op that was used in an operator expression such
2828/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2829/// CandidateSet will store the added overload candidates. (C++
2830/// [over.match.oper]).
2831void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2832 SourceLocation OpLoc,
2833 Expr **Args, unsigned NumArgs,
2834 OverloadCandidateSet& CandidateSet,
2835 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002836 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2837
2838 // C++ [over.match.oper]p3:
2839 // For a unary operator @ with an operand of a type whose
2840 // cv-unqualified version is T1, and for a binary operator @ with
2841 // a left operand of a type whose cv-unqualified version is T1 and
2842 // a right operand of a type whose cv-unqualified version is T2,
2843 // three sets of candidate functions, designated member
2844 // candidates, non-member candidates and built-in candidates, are
2845 // constructed as follows:
2846 QualType T1 = Args[0]->getType();
2847 QualType T2;
2848 if (NumArgs > 1)
2849 T2 = Args[1]->getType();
2850
2851 // -- If T1 is a class type, the set of member candidates is the
2852 // result of the qualified lookup of T1::operator@
2853 // (13.3.1.1.1); otherwise, the set of member candidates is
2854 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00002855 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002856 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00002857 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002858 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002859
John McCalla24dc2e2009-11-17 02:14:36 +00002860 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
2861 LookupQualifiedName(Operators, T1Rec->getDecl());
2862 Operators.suppressDiagnostics();
2863
Mike Stump1eb44332009-09-09 15:08:12 +00002864 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002865 OperEnd = Operators.end();
2866 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00002867 ++Oper)
2868 AddMethodCandidate(*Oper, Args[0], Args + 1, NumArgs - 1, CandidateSet,
2869 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00002870 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002871}
2872
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002873/// AddBuiltinCandidate - Add a candidate for a built-in
2874/// operator. ResultTy and ParamTys are the result and parameter types
2875/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002876/// arguments being passed to the candidate. IsAssignmentOperator
2877/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002878/// operator. NumContextualBoolArguments is the number of arguments
2879/// (at the beginning of the argument list) that will be contextually
2880/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00002881void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002882 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002883 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002884 bool IsAssignmentOperator,
2885 unsigned NumContextualBoolArguments) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002886 // Add this candidate
2887 CandidateSet.push_back(OverloadCandidate());
2888 OverloadCandidate& Candidate = CandidateSet.back();
2889 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00002890 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002891 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002892 Candidate.BuiltinTypes.ResultTy = ResultTy;
2893 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2894 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2895
2896 // Determine the implicit conversion sequences for each of the
2897 // arguments.
2898 Candidate.Viable = true;
2899 Candidate.Conversions.resize(NumArgs);
2900 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002901 // C++ [over.match.oper]p4:
2902 // For the built-in assignment operators, conversions of the
2903 // left operand are restricted as follows:
2904 // -- no temporaries are introduced to hold the left operand, and
2905 // -- no user-defined conversions are applied to the left
2906 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00002907 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002908 //
2909 // We block these conversions by turning off user-defined
2910 // conversions, since that is the only way that initialization of
2911 // a reference to a non-class type can occur from something that
2912 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002913 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00002914 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002915 "Contextual conversion to bool requires bool type");
2916 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2917 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002918 Candidate.Conversions[ArgIdx]
2919 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00002920 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002921 /*ForceRValue=*/false,
2922 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002923 }
Mike Stump1eb44332009-09-09 15:08:12 +00002924 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002925 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002926 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002927 break;
2928 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002929 }
2930}
2931
2932/// BuiltinCandidateTypeSet - A set of types that will be used for the
2933/// candidate operator functions for built-in operators (C++
2934/// [over.built]). The types are separated into pointer types and
2935/// enumeration types.
2936class BuiltinCandidateTypeSet {
2937 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002938 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002939
2940 /// PointerTypes - The set of pointer types that will be used in the
2941 /// built-in candidates.
2942 TypeSet PointerTypes;
2943
Sebastian Redl78eb8742009-04-19 21:53:20 +00002944 /// MemberPointerTypes - The set of member pointer types that will be
2945 /// used in the built-in candidates.
2946 TypeSet MemberPointerTypes;
2947
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002948 /// EnumerationTypes - The set of enumeration types that will be
2949 /// used in the built-in candidates.
2950 TypeSet EnumerationTypes;
2951
Douglas Gregor5842ba92009-08-24 15:23:48 +00002952 /// Sema - The semantic analysis instance where we are building the
2953 /// candidate type set.
2954 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00002955
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002956 /// Context - The AST context in which we will build the type sets.
2957 ASTContext &Context;
2958
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00002959 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
2960 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00002961 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002962
2963public:
2964 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002965 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002966
Mike Stump1eb44332009-09-09 15:08:12 +00002967 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00002968 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002969
Douglas Gregor573d9c32009-10-21 23:19:44 +00002970 void AddTypesConvertedFrom(QualType Ty,
2971 SourceLocation Loc,
2972 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00002973 bool AllowExplicitConversions,
2974 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002975
2976 /// pointer_begin - First pointer type found;
2977 iterator pointer_begin() { return PointerTypes.begin(); }
2978
Sebastian Redl78eb8742009-04-19 21:53:20 +00002979 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002980 iterator pointer_end() { return PointerTypes.end(); }
2981
Sebastian Redl78eb8742009-04-19 21:53:20 +00002982 /// member_pointer_begin - First member pointer type found;
2983 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2984
2985 /// member_pointer_end - Past the last member pointer type found;
2986 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2987
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002988 /// enumeration_begin - First enumeration type found;
2989 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2990
Sebastian Redl78eb8742009-04-19 21:53:20 +00002991 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002992 iterator enumeration_end() { return EnumerationTypes.end(); }
2993};
2994
Sebastian Redl78eb8742009-04-19 21:53:20 +00002995/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002996/// the set of pointer types along with any more-qualified variants of
2997/// that type. For example, if @p Ty is "int const *", this routine
2998/// will add "int const *", "int const volatile *", "int const
2999/// restrict *", and "int const volatile restrict *" to the set of
3000/// pointer types. Returns true if the add of @p Ty itself succeeded,
3001/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003002///
3003/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003004bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00003005BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3006 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00003007
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003008 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003009 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003010 return false;
3011
John McCall0953e762009-09-24 19:53:00 +00003012 const PointerType *PointerTy = Ty->getAs<PointerType>();
3013 assert(PointerTy && "type was not a pointer type!");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003014
John McCall0953e762009-09-24 19:53:00 +00003015 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003016 // Don't add qualified variants of arrays. For one, they're not allowed
3017 // (the qualifier would sink to the element type), and for another, the
3018 // only overload situation where it matters is subscript or pointer +- int,
3019 // and those shouldn't have qualifier variants anyway.
3020 if (PointeeTy->isArrayType())
3021 return true;
John McCall0953e762009-09-24 19:53:00 +00003022 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00003023 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00003024 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003025 bool hasVolatile = VisibleQuals.hasVolatile();
3026 bool hasRestrict = VisibleQuals.hasRestrict();
3027
John McCall0953e762009-09-24 19:53:00 +00003028 // Iterate through all strict supersets of BaseCVR.
3029 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3030 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003031 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3032 // in the types.
3033 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3034 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00003035 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3036 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003037 }
3038
3039 return true;
3040}
3041
Sebastian Redl78eb8742009-04-19 21:53:20 +00003042/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3043/// to the set of pointer types along with any more-qualified variants of
3044/// that type. For example, if @p Ty is "int const *", this routine
3045/// will add "int const *", "int const volatile *", "int const
3046/// restrict *", and "int const volatile restrict *" to the set of
3047/// pointer types. Returns true if the add of @p Ty itself succeeded,
3048/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003049///
3050/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003051bool
3052BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3053 QualType Ty) {
3054 // Insert this type.
3055 if (!MemberPointerTypes.insert(Ty))
3056 return false;
3057
John McCall0953e762009-09-24 19:53:00 +00003058 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3059 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00003060
John McCall0953e762009-09-24 19:53:00 +00003061 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003062 // Don't add qualified variants of arrays. For one, they're not allowed
3063 // (the qualifier would sink to the element type), and for another, the
3064 // only overload situation where it matters is subscript or pointer +- int,
3065 // and those shouldn't have qualifier variants anyway.
3066 if (PointeeTy->isArrayType())
3067 return true;
John McCall0953e762009-09-24 19:53:00 +00003068 const Type *ClassTy = PointerTy->getClass();
3069
3070 // Iterate through all strict supersets of the pointee type's CVR
3071 // qualifiers.
3072 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3073 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3074 if ((CVR | BaseCVR) != CVR) continue;
3075
3076 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3077 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00003078 }
3079
3080 return true;
3081}
3082
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003083/// AddTypesConvertedFrom - Add each of the types to which the type @p
3084/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00003085/// primarily interested in pointer types and enumeration types. We also
3086/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003087/// AllowUserConversions is true if we should look at the conversion
3088/// functions of a class type, and AllowExplicitConversions if we
3089/// should also include the explicit conversion functions of a class
3090/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003091void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003092BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003093 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003094 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003095 bool AllowExplicitConversions,
3096 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003097 // Only deal with canonical types.
3098 Ty = Context.getCanonicalType(Ty);
3099
3100 // Look through reference types; they aren't part of the type of an
3101 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00003102 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003103 Ty = RefTy->getPointeeType();
3104
3105 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003106 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003107
Sebastian Redla65b5512009-11-05 16:36:20 +00003108 // If we're dealing with an array type, decay to the pointer.
3109 if (Ty->isArrayType())
3110 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3111
Ted Kremenek6217b802009-07-29 21:53:49 +00003112 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003113 QualType PointeeTy = PointerTy->getPointeeType();
3114
3115 // Insert our type, and its more-qualified variants, into the set
3116 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003117 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003118 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00003119 } else if (Ty->isMemberPointerType()) {
3120 // Member pointers are far easier, since the pointee can't be converted.
3121 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3122 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003123 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00003124 EnumerationTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003125 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003126 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003127 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003128 // No conversion functions in incomplete types.
3129 return;
3130 }
Mike Stump1eb44332009-09-09 15:08:12 +00003131
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003132 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallba135432009-11-21 08:51:07 +00003133 const UnresolvedSet *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00003134 = ClassDecl->getVisibleConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00003135 for (UnresolvedSet::iterator I = Conversions->begin(),
3136 E = Conversions->end(); I != E; ++I) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003137
Mike Stump1eb44332009-09-09 15:08:12 +00003138 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003139 // about which builtin types we can convert to.
John McCallba135432009-11-21 08:51:07 +00003140 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003141 continue;
3142
John McCallba135432009-11-21 08:51:07 +00003143 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003144 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003145 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003146 VisibleQuals);
3147 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003148 }
3149 }
3150 }
3151}
3152
Douglas Gregor19b7b152009-08-24 13:43:27 +00003153/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3154/// the volatile- and non-volatile-qualified assignment operators for the
3155/// given type to the candidate set.
3156static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3157 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00003158 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003159 unsigned NumArgs,
3160 OverloadCandidateSet &CandidateSet) {
3161 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00003162
Douglas Gregor19b7b152009-08-24 13:43:27 +00003163 // T& operator=(T&, T)
3164 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3165 ParamTypes[1] = T;
3166 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3167 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003168
Douglas Gregor19b7b152009-08-24 13:43:27 +00003169 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3170 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00003171 ParamTypes[0]
3172 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00003173 ParamTypes[1] = T;
3174 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00003175 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003176 }
3177}
Mike Stump1eb44332009-09-09 15:08:12 +00003178
Sebastian Redl9994a342009-10-25 17:03:50 +00003179/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3180/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003181static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3182 Qualifiers VRQuals;
3183 const RecordType *TyRec;
3184 if (const MemberPointerType *RHSMPType =
3185 ArgExpr->getType()->getAs<MemberPointerType>())
3186 TyRec = cast<RecordType>(RHSMPType->getClass());
3187 else
3188 TyRec = ArgExpr->getType()->getAs<RecordType>();
3189 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003190 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003191 VRQuals.addVolatile();
3192 VRQuals.addRestrict();
3193 return VRQuals;
3194 }
3195
3196 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallba135432009-11-21 08:51:07 +00003197 const UnresolvedSet *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00003198 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003199
John McCallba135432009-11-21 08:51:07 +00003200 for (UnresolvedSet::iterator I = Conversions->begin(),
3201 E = Conversions->end(); I != E; ++I) {
3202 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003203 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3204 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3205 CanTy = ResTypeRef->getPointeeType();
3206 // Need to go down the pointer/mempointer chain and add qualifiers
3207 // as see them.
3208 bool done = false;
3209 while (!done) {
3210 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3211 CanTy = ResTypePtr->getPointeeType();
3212 else if (const MemberPointerType *ResTypeMPtr =
3213 CanTy->getAs<MemberPointerType>())
3214 CanTy = ResTypeMPtr->getPointeeType();
3215 else
3216 done = true;
3217 if (CanTy.isVolatileQualified())
3218 VRQuals.addVolatile();
3219 if (CanTy.isRestrictQualified())
3220 VRQuals.addRestrict();
3221 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3222 return VRQuals;
3223 }
3224 }
3225 }
3226 return VRQuals;
3227}
3228
Douglas Gregor74253732008-11-19 15:42:04 +00003229/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3230/// operator overloads to the candidate set (C++ [over.built]), based
3231/// on the operator @p Op and the arguments given. For example, if the
3232/// operator is a binary '+', this routine might add "int
3233/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003234void
Mike Stump1eb44332009-09-09 15:08:12 +00003235Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003236 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00003237 Expr **Args, unsigned NumArgs,
3238 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003239 // The set of "promoted arithmetic types", which are the arithmetic
3240 // types are that preserved by promotion (C++ [over.built]p2). Note
3241 // that the first few of these types are the promoted integral
3242 // types; these types need to be first.
3243 // FIXME: What about complex?
3244 const unsigned FirstIntegralType = 0;
3245 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00003246 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003247 LastPromotedIntegralType = 13;
3248 const unsigned FirstPromotedArithmeticType = 7,
3249 LastPromotedArithmeticType = 16;
3250 const unsigned NumArithmeticTypes = 16;
3251 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00003252 Context.BoolTy, Context.CharTy, Context.WCharTy,
3253// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003254 Context.SignedCharTy, Context.ShortTy,
3255 Context.UnsignedCharTy, Context.UnsignedShortTy,
3256 Context.IntTy, Context.LongTy, Context.LongLongTy,
3257 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3258 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3259 };
Douglas Gregor652371a2009-10-21 22:01:30 +00003260 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3261 "Invalid first promoted integral type");
3262 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3263 == Context.UnsignedLongLongTy &&
3264 "Invalid last promoted integral type");
3265 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3266 "Invalid first promoted arithmetic type");
3267 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3268 == Context.LongDoubleTy &&
3269 "Invalid last promoted arithmetic type");
3270
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003271 // Find all of the types that the arguments can convert to, but only
3272 // if the operator we're looking at has built-in operator candidates
3273 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003274 Qualifiers VisibleTypeConversionsQuals;
3275 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003276 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3277 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3278
Douglas Gregor5842ba92009-08-24 15:23:48 +00003279 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003280 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3281 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00003282 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003283 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00003284 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003285 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor74253732008-11-19 15:42:04 +00003286 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003287 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregor573d9c32009-10-21 23:19:44 +00003288 OpLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003289 true,
3290 (Op == OO_Exclaim ||
3291 Op == OO_AmpAmp ||
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003292 Op == OO_PipePipe),
3293 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003294 }
3295
3296 bool isComparison = false;
3297 switch (Op) {
3298 case OO_None:
3299 case NUM_OVERLOADED_OPERATORS:
3300 assert(false && "Expected an overloaded operator");
3301 break;
3302
Douglas Gregor74253732008-11-19 15:42:04 +00003303 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00003304 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00003305 goto UnaryStar;
3306 else
3307 goto BinaryStar;
3308 break;
3309
3310 case OO_Plus: // '+' is either unary or binary
3311 if (NumArgs == 1)
3312 goto UnaryPlus;
3313 else
3314 goto BinaryPlus;
3315 break;
3316
3317 case OO_Minus: // '-' is either unary or binary
3318 if (NumArgs == 1)
3319 goto UnaryMinus;
3320 else
3321 goto BinaryMinus;
3322 break;
3323
3324 case OO_Amp: // '&' is either unary or binary
3325 if (NumArgs == 1)
3326 goto UnaryAmp;
3327 else
3328 goto BinaryAmp;
3329
3330 case OO_PlusPlus:
3331 case OO_MinusMinus:
3332 // C++ [over.built]p3:
3333 //
3334 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3335 // is either volatile or empty, there exist candidate operator
3336 // functions of the form
3337 //
3338 // VQ T& operator++(VQ T&);
3339 // T operator++(VQ T&, int);
3340 //
3341 // C++ [over.built]p4:
3342 //
3343 // For every pair (T, VQ), where T is an arithmetic type other
3344 // than bool, and VQ is either volatile or empty, there exist
3345 // candidate operator functions of the form
3346 //
3347 // VQ T& operator--(VQ T&);
3348 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00003349 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00003350 Arith < NumArithmeticTypes; ++Arith) {
3351 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00003352 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003353 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00003354
3355 // Non-volatile version.
3356 if (NumArgs == 1)
3357 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3358 else
3359 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003360 // heuristic to reduce number of builtin candidates in the set.
3361 // Add volatile version only if there are conversions to a volatile type.
3362 if (VisibleTypeConversionsQuals.hasVolatile()) {
3363 // Volatile version
3364 ParamTypes[0]
3365 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3366 if (NumArgs == 1)
3367 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3368 else
3369 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3370 }
Douglas Gregor74253732008-11-19 15:42:04 +00003371 }
3372
3373 // C++ [over.built]p5:
3374 //
3375 // For every pair (T, VQ), where T is a cv-qualified or
3376 // cv-unqualified object type, and VQ is either volatile or
3377 // empty, there exist candidate operator functions of the form
3378 //
3379 // T*VQ& operator++(T*VQ&);
3380 // T*VQ& operator--(T*VQ&);
3381 // T* operator++(T*VQ&, int);
3382 // T* operator--(T*VQ&, int);
3383 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3384 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3385 // Skip pointer types that aren't pointers to object types.
Ted Kremenek6217b802009-07-29 21:53:49 +00003386 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00003387 continue;
3388
Mike Stump1eb44332009-09-09 15:08:12 +00003389 QualType ParamTypes[2] = {
3390 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00003391 };
Mike Stump1eb44332009-09-09 15:08:12 +00003392
Douglas Gregor74253732008-11-19 15:42:04 +00003393 // Without volatile
3394 if (NumArgs == 1)
3395 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3396 else
3397 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3398
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003399 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3400 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003401 // With volatile
John McCall0953e762009-09-24 19:53:00 +00003402 ParamTypes[0]
3403 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00003404 if (NumArgs == 1)
3405 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3406 else
3407 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3408 }
3409 }
3410 break;
3411
3412 UnaryStar:
3413 // C++ [over.built]p6:
3414 // For every cv-qualified or cv-unqualified object type T, there
3415 // exist candidate operator functions of the form
3416 //
3417 // T& operator*(T*);
3418 //
3419 // C++ [over.built]p7:
3420 // For every function type T, there exist candidate operator
3421 // functions of the form
3422 // T& operator*(T*);
3423 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3424 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3425 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00003426 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003427 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00003428 &ParamTy, Args, 1, CandidateSet);
3429 }
3430 break;
3431
3432 UnaryPlus:
3433 // C++ [over.built]p8:
3434 // For every type T, there exist candidate operator functions of
3435 // the form
3436 //
3437 // T* operator+(T*);
3438 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3439 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3440 QualType ParamTy = *Ptr;
3441 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3442 }
Mike Stump1eb44332009-09-09 15:08:12 +00003443
Douglas Gregor74253732008-11-19 15:42:04 +00003444 // Fall through
3445
3446 UnaryMinus:
3447 // C++ [over.built]p9:
3448 // For every promoted arithmetic type T, there exist candidate
3449 // operator functions of the form
3450 //
3451 // T operator+(T);
3452 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003453 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00003454 Arith < LastPromotedArithmeticType; ++Arith) {
3455 QualType ArithTy = ArithmeticTypes[Arith];
3456 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3457 }
3458 break;
3459
3460 case OO_Tilde:
3461 // C++ [over.built]p10:
3462 // For every promoted integral type T, there exist candidate
3463 // operator functions of the form
3464 //
3465 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003466 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00003467 Int < LastPromotedIntegralType; ++Int) {
3468 QualType IntTy = ArithmeticTypes[Int];
3469 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3470 }
3471 break;
3472
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003473 case OO_New:
3474 case OO_Delete:
3475 case OO_Array_New:
3476 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003477 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00003478 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003479 break;
3480
3481 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00003482 UnaryAmp:
3483 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003484 // C++ [over.match.oper]p3:
3485 // -- For the operator ',', the unary operator '&', or the
3486 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003487 break;
3488
Douglas Gregor19b7b152009-08-24 13:43:27 +00003489 case OO_EqualEqual:
3490 case OO_ExclaimEqual:
3491 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00003492 // For every pointer to member type T, there exist candidate operator
3493 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00003494 //
3495 // bool operator==(T,T);
3496 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00003497 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00003498 MemPtr = CandidateTypes.member_pointer_begin(),
3499 MemPtrEnd = CandidateTypes.member_pointer_end();
3500 MemPtr != MemPtrEnd;
3501 ++MemPtr) {
3502 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3503 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3504 }
Mike Stump1eb44332009-09-09 15:08:12 +00003505
Douglas Gregor19b7b152009-08-24 13:43:27 +00003506 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00003507
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003508 case OO_Less:
3509 case OO_Greater:
3510 case OO_LessEqual:
3511 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003512 // C++ [over.built]p15:
3513 //
3514 // For every pointer or enumeration type T, there exist
3515 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003516 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003517 // bool operator<(T, T);
3518 // bool operator>(T, T);
3519 // bool operator<=(T, T);
3520 // bool operator>=(T, T);
3521 // bool operator==(T, T);
3522 // bool operator!=(T, T);
3523 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3524 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3525 QualType ParamTypes[2] = { *Ptr, *Ptr };
3526 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3527 }
Mike Stump1eb44332009-09-09 15:08:12 +00003528 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003529 = CandidateTypes.enumeration_begin();
3530 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3531 QualType ParamTypes[2] = { *Enum, *Enum };
3532 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3533 }
3534
3535 // Fall through.
3536 isComparison = true;
3537
Douglas Gregor74253732008-11-19 15:42:04 +00003538 BinaryPlus:
3539 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003540 if (!isComparison) {
3541 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3542
3543 // C++ [over.built]p13:
3544 //
3545 // For every cv-qualified or cv-unqualified object type T
3546 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003547 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003548 // T* operator+(T*, ptrdiff_t);
3549 // T& operator[](T*, ptrdiff_t); [BELOW]
3550 // T* operator-(T*, ptrdiff_t);
3551 // T* operator+(ptrdiff_t, T*);
3552 // T& operator[](ptrdiff_t, T*); [BELOW]
3553 //
3554 // C++ [over.built]p14:
3555 //
3556 // For every T, where T is a pointer to object type, there
3557 // exist candidate operator functions of the form
3558 //
3559 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00003560 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003561 = CandidateTypes.pointer_begin();
3562 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3563 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3564
3565 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3566 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3567
3568 if (Op == OO_Plus) {
3569 // T* operator+(ptrdiff_t, T*);
3570 ParamTypes[0] = ParamTypes[1];
3571 ParamTypes[1] = *Ptr;
3572 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3573 } else {
3574 // ptrdiff_t operator-(T, T);
3575 ParamTypes[1] = *Ptr;
3576 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3577 Args, 2, CandidateSet);
3578 }
3579 }
3580 }
3581 // Fall through
3582
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003583 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00003584 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003585 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003586 // C++ [over.built]p12:
3587 //
3588 // For every pair of promoted arithmetic types L and R, there
3589 // exist candidate operator functions of the form
3590 //
3591 // LR operator*(L, R);
3592 // LR operator/(L, R);
3593 // LR operator+(L, R);
3594 // LR operator-(L, R);
3595 // bool operator<(L, R);
3596 // bool operator>(L, R);
3597 // bool operator<=(L, R);
3598 // bool operator>=(L, R);
3599 // bool operator==(L, R);
3600 // bool operator!=(L, R);
3601 //
3602 // where LR is the result of the usual arithmetic conversions
3603 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003604 //
3605 // C++ [over.built]p24:
3606 //
3607 // For every pair of promoted arithmetic types L and R, there exist
3608 // candidate operator functions of the form
3609 //
3610 // LR operator?(bool, L, R);
3611 //
3612 // where LR is the result of the usual arithmetic conversions
3613 // between types L and R.
3614 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003615 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003616 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003617 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003618 Right < LastPromotedArithmeticType; ++Right) {
3619 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00003620 QualType Result
3621 = isComparison
3622 ? Context.BoolTy
3623 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003624 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3625 }
3626 }
3627 break;
3628
3629 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00003630 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003631 case OO_Caret:
3632 case OO_Pipe:
3633 case OO_LessLess:
3634 case OO_GreaterGreater:
3635 // C++ [over.built]p17:
3636 //
3637 // For every pair of promoted integral types L and R, there
3638 // exist candidate operator functions of the form
3639 //
3640 // LR operator%(L, R);
3641 // LR operator&(L, R);
3642 // LR operator^(L, R);
3643 // LR operator|(L, R);
3644 // L operator<<(L, R);
3645 // L operator>>(L, R);
3646 //
3647 // where LR is the result of the usual arithmetic conversions
3648 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00003649 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003650 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003651 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003652 Right < LastPromotedIntegralType; ++Right) {
3653 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3654 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3655 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00003656 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003657 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3658 }
3659 }
3660 break;
3661
3662 case OO_Equal:
3663 // C++ [over.built]p20:
3664 //
3665 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00003666 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003667 // empty, there exist candidate operator functions of the form
3668 //
3669 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003670 for (BuiltinCandidateTypeSet::iterator
3671 Enum = CandidateTypes.enumeration_begin(),
3672 EnumEnd = CandidateTypes.enumeration_end();
3673 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00003674 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003675 CandidateSet);
3676 for (BuiltinCandidateTypeSet::iterator
3677 MemPtr = CandidateTypes.member_pointer_begin(),
3678 MemPtrEnd = CandidateTypes.member_pointer_end();
3679 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00003680 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003681 CandidateSet);
3682 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003683
3684 case OO_PlusEqual:
3685 case OO_MinusEqual:
3686 // C++ [over.built]p19:
3687 //
3688 // For every pair (T, VQ), where T is any type and VQ is either
3689 // volatile or empty, there exist candidate operator functions
3690 // of the form
3691 //
3692 // T*VQ& operator=(T*VQ&, T*);
3693 //
3694 // C++ [over.built]p21:
3695 //
3696 // For every pair (T, VQ), where T is a cv-qualified or
3697 // cv-unqualified object type and VQ is either volatile or
3698 // empty, there exist candidate operator functions of the form
3699 //
3700 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3701 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3702 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3703 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3704 QualType ParamTypes[2];
3705 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3706
3707 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003708 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003709 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3710 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003711
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003712 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3713 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003714 // volatile version
John McCall0953e762009-09-24 19:53:00 +00003715 ParamTypes[0]
3716 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003717 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3718 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003719 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003720 }
3721 // Fall through.
3722
3723 case OO_StarEqual:
3724 case OO_SlashEqual:
3725 // C++ [over.built]p18:
3726 //
3727 // For every triple (L, VQ, R), where L is an arithmetic type,
3728 // VQ is either volatile or empty, and R is a promoted
3729 // arithmetic type, there exist candidate operator functions of
3730 // the form
3731 //
3732 // VQ L& operator=(VQ L&, R);
3733 // VQ L& operator*=(VQ L&, R);
3734 // VQ L& operator/=(VQ L&, R);
3735 // VQ L& operator+=(VQ L&, R);
3736 // VQ L& operator-=(VQ L&, R);
3737 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003738 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003739 Right < LastPromotedArithmeticType; ++Right) {
3740 QualType ParamTypes[2];
3741 ParamTypes[1] = ArithmeticTypes[Right];
3742
3743 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003744 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003745 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3746 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003747
3748 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003749 if (VisibleTypeConversionsQuals.hasVolatile()) {
3750 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3751 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3752 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3753 /*IsAssigmentOperator=*/Op == OO_Equal);
3754 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003755 }
3756 }
3757 break;
3758
3759 case OO_PercentEqual:
3760 case OO_LessLessEqual:
3761 case OO_GreaterGreaterEqual:
3762 case OO_AmpEqual:
3763 case OO_CaretEqual:
3764 case OO_PipeEqual:
3765 // C++ [over.built]p22:
3766 //
3767 // For every triple (L, VQ, R), where L is an integral type, VQ
3768 // is either volatile or empty, and R is a promoted integral
3769 // type, there exist candidate operator functions of the form
3770 //
3771 // VQ L& operator%=(VQ L&, R);
3772 // VQ L& operator<<=(VQ L&, R);
3773 // VQ L& operator>>=(VQ L&, R);
3774 // VQ L& operator&=(VQ L&, R);
3775 // VQ L& operator^=(VQ L&, R);
3776 // VQ L& operator|=(VQ L&, R);
3777 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003778 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003779 Right < LastPromotedIntegralType; ++Right) {
3780 QualType ParamTypes[2];
3781 ParamTypes[1] = ArithmeticTypes[Right];
3782
3783 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003784 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003785 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00003786 if (VisibleTypeConversionsQuals.hasVolatile()) {
3787 // Add this built-in operator as a candidate (VQ is 'volatile').
3788 ParamTypes[0] = ArithmeticTypes[Left];
3789 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3790 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3791 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3792 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003793 }
3794 }
3795 break;
3796
Douglas Gregor74253732008-11-19 15:42:04 +00003797 case OO_Exclaim: {
3798 // C++ [over.operator]p23:
3799 //
3800 // There also exist candidate operator functions of the form
3801 //
Mike Stump1eb44332009-09-09 15:08:12 +00003802 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00003803 // bool operator&&(bool, bool); [BELOW]
3804 // bool operator||(bool, bool); [BELOW]
3805 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003806 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3807 /*IsAssignmentOperator=*/false,
3808 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00003809 break;
3810 }
3811
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003812 case OO_AmpAmp:
3813 case OO_PipePipe: {
3814 // C++ [over.operator]p23:
3815 //
3816 // There also exist candidate operator functions of the form
3817 //
Douglas Gregor74253732008-11-19 15:42:04 +00003818 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003819 // bool operator&&(bool, bool);
3820 // bool operator||(bool, bool);
3821 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003822 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3823 /*IsAssignmentOperator=*/false,
3824 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003825 break;
3826 }
3827
3828 case OO_Subscript:
3829 // C++ [over.built]p13:
3830 //
3831 // For every cv-qualified or cv-unqualified object type T there
3832 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003833 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003834 // T* operator+(T*, ptrdiff_t); [ABOVE]
3835 // T& operator[](T*, ptrdiff_t);
3836 // T* operator-(T*, ptrdiff_t); [ABOVE]
3837 // T* operator+(ptrdiff_t, T*); [ABOVE]
3838 // T& operator[](ptrdiff_t, T*);
3839 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3840 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3841 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00003842 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003843 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003844
3845 // T& operator[](T*, ptrdiff_t)
3846 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3847
3848 // T& operator[](ptrdiff_t, T*);
3849 ParamTypes[0] = ParamTypes[1];
3850 ParamTypes[1] = *Ptr;
3851 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3852 }
3853 break;
3854
3855 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003856 // C++ [over.built]p11:
3857 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3858 // C1 is the same type as C2 or is a derived class of C2, T is an object
3859 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3860 // there exist candidate operator functions of the form
3861 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3862 // where CV12 is the union of CV1 and CV2.
3863 {
3864 for (BuiltinCandidateTypeSet::iterator Ptr =
3865 CandidateTypes.pointer_begin();
3866 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3867 QualType C1Ty = (*Ptr);
3868 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00003869 QualifierCollector Q1;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003870 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00003871 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003872 if (!isa<RecordType>(C1))
3873 continue;
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003874 // heuristic to reduce number of builtin candidates in the set.
3875 // Add volatile/restrict version only if there are conversions to a
3876 // volatile/restrict type.
3877 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3878 continue;
3879 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3880 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003881 }
3882 for (BuiltinCandidateTypeSet::iterator
3883 MemPtr = CandidateTypes.member_pointer_begin(),
3884 MemPtrEnd = CandidateTypes.member_pointer_end();
3885 MemPtr != MemPtrEnd; ++MemPtr) {
3886 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3887 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00003888 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003889 if (C1 != C2 && !IsDerivedFrom(C1, C2))
3890 break;
3891 QualType ParamTypes[2] = { *Ptr, *MemPtr };
3892 // build CV12 T&
3893 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003894 if (!VisibleTypeConversionsQuals.hasVolatile() &&
3895 T.isVolatileQualified())
3896 continue;
3897 if (!VisibleTypeConversionsQuals.hasRestrict() &&
3898 T.isRestrictQualified())
3899 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00003900 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003901 QualType ResultTy = Context.getLValueReferenceType(T);
3902 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3903 }
3904 }
3905 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003906 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003907
3908 case OO_Conditional:
3909 // Note that we don't consider the first argument, since it has been
3910 // contextually converted to bool long ago. The candidates below are
3911 // therefore added as binary.
3912 //
3913 // C++ [over.built]p24:
3914 // For every type T, where T is a pointer or pointer-to-member type,
3915 // there exist candidate operator functions of the form
3916 //
3917 // T operator?(bool, T, T);
3918 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003919 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3920 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3921 QualType ParamTypes[2] = { *Ptr, *Ptr };
3922 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3923 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00003924 for (BuiltinCandidateTypeSet::iterator Ptr =
3925 CandidateTypes.member_pointer_begin(),
3926 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3927 QualType ParamTypes[2] = { *Ptr, *Ptr };
3928 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3929 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003930 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003931 }
3932}
3933
Douglas Gregorfa047642009-02-04 00:32:51 +00003934/// \brief Add function candidates found via argument-dependent lookup
3935/// to the set of overloading candidates.
3936///
3937/// This routine performs argument-dependent name lookup based on the
3938/// given function name (which may also be an operator name) and adds
3939/// all of the overload candidates found by ADL to the overload
3940/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00003941void
Douglas Gregorfa047642009-02-04 00:32:51 +00003942Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3943 Expr **Args, unsigned NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003944 bool HasExplicitTemplateArgs,
John McCall833ca992009-10-29 08:12:44 +00003945 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003946 unsigned NumExplicitTemplateArgs,
3947 OverloadCandidateSet& CandidateSet,
3948 bool PartialOverloading) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003949 FunctionSet Functions;
Douglas Gregorfa047642009-02-04 00:32:51 +00003950
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003951 // FIXME: Should we be trafficking in canonical function decls throughout?
3952
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003953 // Record all of the function candidates that we've already
3954 // added to the overload set, so that we don't add those same
3955 // candidates a second time.
3956 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3957 CandEnd = CandidateSet.end();
3958 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00003959 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003960 Functions.insert(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00003961 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3962 Functions.insert(FunTmpl);
3963 }
Douglas Gregorfa047642009-02-04 00:32:51 +00003964
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003965 // FIXME: Pass in the explicit template arguments?
Sebastian Redl644be852009-10-23 19:23:15 +00003966 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregorfa047642009-02-04 00:32:51 +00003967
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003968 // Erase all of the candidates we already knew about.
3969 // FIXME: This is suboptimal. Is there a better way?
3970 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3971 CandEnd = CandidateSet.end();
3972 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00003973 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003974 Functions.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00003975 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3976 Functions.erase(FunTmpl);
3977 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003978
3979 // For each of the ADL candidates we found, add it to the overload
3980 // set.
3981 for (FunctionSet::iterator Func = Functions.begin(),
3982 FuncEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00003983 Func != FuncEnd; ++Func) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003984 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
3985 if (HasExplicitTemplateArgs)
3986 continue;
3987
3988 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
3989 false, false, PartialOverloading);
3990 } else
Mike Stump1eb44332009-09-09 15:08:12 +00003991 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003992 HasExplicitTemplateArgs,
3993 ExplicitTemplateArgs,
3994 NumExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003995 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00003996 }
Douglas Gregorfa047642009-02-04 00:32:51 +00003997}
3998
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003999/// isBetterOverloadCandidate - Determines whether the first overload
4000/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00004001bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004002Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump1eb44332009-09-09 15:08:12 +00004003 const OverloadCandidate& Cand2) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004004 // Define viable functions to be better candidates than non-viable
4005 // functions.
4006 if (!Cand2.Viable)
4007 return Cand1.Viable;
4008 else if (!Cand1.Viable)
4009 return false;
4010
Douglas Gregor88a35142008-12-22 05:46:06 +00004011 // C++ [over.match.best]p1:
4012 //
4013 // -- if F is a static member function, ICS1(F) is defined such
4014 // that ICS1(F) is neither better nor worse than ICS1(G) for
4015 // any function G, and, symmetrically, ICS1(G) is neither
4016 // better nor worse than ICS1(F).
4017 unsigned StartArg = 0;
4018 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4019 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004020
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004021 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00004022 // A viable function F1 is defined to be a better function than another
4023 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004024 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004025 unsigned NumArgs = Cand1.Conversions.size();
4026 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4027 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004028 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004029 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4030 Cand2.Conversions[ArgIdx])) {
4031 case ImplicitConversionSequence::Better:
4032 // Cand1 has a better conversion sequence.
4033 HasBetterConversion = true;
4034 break;
4035
4036 case ImplicitConversionSequence::Worse:
4037 // Cand1 can't be better than Cand2.
4038 return false;
4039
4040 case ImplicitConversionSequence::Indistinguishable:
4041 // Do nothing.
4042 break;
4043 }
4044 }
4045
Mike Stump1eb44332009-09-09 15:08:12 +00004046 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004047 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004048 if (HasBetterConversion)
4049 return true;
4050
Mike Stump1eb44332009-09-09 15:08:12 +00004051 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004052 // specialization, or, if not that,
4053 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4054 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4055 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004056
4057 // -- F1 and F2 are function template specializations, and the function
4058 // template for F1 is more specialized than the template for F2
4059 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004060 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00004061 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4062 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004063 if (FunctionTemplateDecl *BetterTemplate
4064 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4065 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor5d7d3752009-09-14 23:02:14 +00004066 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4067 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004068 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004069
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004070 // -- the context is an initialization by user-defined conversion
4071 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4072 // from the return type of F1 to the destination type (i.e.,
4073 // the type of the entity being initialized) is a better
4074 // conversion sequence than the standard conversion sequence
4075 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00004076 if (Cand1.Function && Cand2.Function &&
4077 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004078 isa<CXXConversionDecl>(Cand2.Function)) {
4079 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4080 Cand2.FinalConversion)) {
4081 case ImplicitConversionSequence::Better:
4082 // Cand1 has a better conversion sequence.
4083 return true;
4084
4085 case ImplicitConversionSequence::Worse:
4086 // Cand1 can't be better than Cand2.
4087 return false;
4088
4089 case ImplicitConversionSequence::Indistinguishable:
4090 // Do nothing
4091 break;
4092 }
4093 }
4094
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004095 return false;
4096}
4097
Mike Stump1eb44332009-09-09 15:08:12 +00004098/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00004099/// within an overload candidate set.
4100///
4101/// \param CandidateSet the set of candidate functions.
4102///
4103/// \param Loc the location of the function name (or operator symbol) for
4104/// which overload resolution occurs.
4105///
Mike Stump1eb44332009-09-09 15:08:12 +00004106/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00004107/// function, Best points to the candidate function found.
4108///
4109/// \returns The result of overload resolution.
Mike Stump1eb44332009-09-09 15:08:12 +00004110Sema::OverloadingResult
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004111Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregore0762c92009-06-19 23:52:42 +00004112 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00004113 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004114 // Find the best viable function.
4115 Best = CandidateSet.end();
4116 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4117 Cand != CandidateSet.end(); ++Cand) {
4118 if (Cand->Viable) {
4119 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4120 Best = Cand;
4121 }
4122 }
4123
4124 // If we didn't find any viable functions, abort.
4125 if (Best == CandidateSet.end())
4126 return OR_No_Viable_Function;
4127
4128 // Make sure that this function is better than every other viable
4129 // function. If not, we have an ambiguity.
4130 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4131 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00004132 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004133 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004134 !isBetterOverloadCandidate(*Best, *Cand)) {
4135 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004136 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004137 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004138 }
Mike Stump1eb44332009-09-09 15:08:12 +00004139
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004140 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004141 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00004142 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004143 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004144 return OR_Deleted;
4145
Douglas Gregore0762c92009-06-19 23:52:42 +00004146 // C++ [basic.def.odr]p2:
4147 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00004148 // when referred to from a potentially-evaluated expression. [Note: this
4149 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00004150 // (clause 13), user-defined conversions (12.3.2), allocation function for
4151 // placement new (5.3.4), as well as non-default initialization (8.5).
4152 if (Best->Function)
4153 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004154 return OR_Success;
4155}
4156
4157/// PrintOverloadCandidates - When overload resolution fails, prints
4158/// diagnostic messages containing the candidates in the candidate
4159/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump1eb44332009-09-09 15:08:12 +00004160void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004161Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00004162 bool OnlyViable,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004163 const char *Opc,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00004164 SourceLocation OpLoc) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004165 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4166 LastCand = CandidateSet.end();
Fariborz Jahanian27687cf2009-10-12 17:51:19 +00004167 bool Reported = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004168 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004169 if (Cand->Viable || !OnlyViable) {
4170 if (Cand->Function) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004171 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004172 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004173 // Deleted or "unavailable" function.
4174 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4175 << Cand->Function->isDeleted();
Douglas Gregor1fdd89b2009-09-15 20:11:42 +00004176 } else if (FunctionTemplateDecl *FunTmpl
4177 = Cand->Function->getPrimaryTemplate()) {
4178 // Function template specialization
4179 // FIXME: Give a better reason!
4180 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4181 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4182 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004183 } else {
4184 // Normal function
Fariborz Jahanianb1663d02009-09-23 00:58:07 +00004185 bool errReported = false;
4186 if (!Cand->Viable && Cand->Conversions.size() > 0) {
4187 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4188 const ImplicitConversionSequence &Conversion =
4189 Cand->Conversions[i];
4190 if ((Conversion.ConversionKind !=
4191 ImplicitConversionSequence::BadConversion) ||
4192 Conversion.ConversionFunctionSet.size() == 0)
4193 continue;
4194 Diag(Cand->Function->getLocation(),
4195 diag::err_ovl_candidate_not_viable) << (i+1);
4196 errReported = true;
4197 for (int j = Conversion.ConversionFunctionSet.size()-1;
4198 j >= 0; j--) {
4199 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4200 Diag(Func->getLocation(), diag::err_ovl_candidate);
4201 }
4202 }
4203 }
4204 if (!errReported)
4205 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004206 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004207 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00004208 // Desugar the type of the surrogate down to a function type,
4209 // retaining as many typedefs as possible while still showing
4210 // the function type (and, therefore, its parameter types).
4211 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004212 bool isLValueReference = false;
4213 bool isRValueReference = false;
Douglas Gregor621b3932008-11-21 02:54:28 +00004214 bool isPointer = false;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004215 if (const LValueReferenceType *FnTypeRef =
Ted Kremenek6217b802009-07-29 21:53:49 +00004216 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00004217 FnType = FnTypeRef->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004218 isLValueReference = true;
4219 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenek6217b802009-07-29 21:53:49 +00004220 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004221 FnType = FnTypeRef->getPointeeType();
4222 isRValueReference = true;
Douglas Gregor621b3932008-11-21 02:54:28 +00004223 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004224 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00004225 FnType = FnTypePtr->getPointeeType();
4226 isPointer = true;
4227 }
4228 // Desugar down to a function type.
John McCall183700f2009-09-21 23:43:11 +00004229 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor621b3932008-11-21 02:54:28 +00004230 // Reconstruct the pointer/reference as appropriate.
4231 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004232 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4233 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor621b3932008-11-21 02:54:28 +00004234
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004235 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00004236 << FnType;
Douglas Gregor33074752009-09-30 21:46:01 +00004237 } else if (OnlyViable) {
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004238 assert(Cand->Conversions.size() <= 2 &&
Fariborz Jahanianad3607d2009-10-09 17:09:58 +00004239 "builtin-binary-operator-not-binary");
Fariborz Jahanian866b2742009-10-16 23:25:02 +00004240 std::string TypeStr("operator");
4241 TypeStr += Opc;
4242 TypeStr += "(";
4243 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4244 if (Cand->Conversions.size() == 1) {
4245 TypeStr += ")";
4246 Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr;
4247 }
4248 else {
4249 TypeStr += ", ";
4250 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4251 TypeStr += ")";
4252 Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr;
4253 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004254 }
Fariborz Jahanian27687cf2009-10-12 17:51:19 +00004255 else if (!Cand->Viable && !Reported) {
4256 // Non-viability might be due to ambiguous user-defined conversions,
4257 // needed for built-in operators. Report them as well, but only once
4258 // as we have typically many built-in candidates.
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004259 unsigned NoOperands = Cand->Conversions.size();
4260 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
Fariborz Jahanian27687cf2009-10-12 17:51:19 +00004261 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4262 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4263 ICS.ConversionFunctionSet.empty())
4264 continue;
4265 if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4266 Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4267 QualType FromTy =
4268 QualType(
4269 static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4270 Diag(OpLoc,diag::note_ambiguous_type_conversion)
4271 << FromTy << Func->getConversionType();
4272 }
4273 for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4274 FunctionDecl *Func =
4275 Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4276 Diag(Func->getLocation(),diag::err_ovl_candidate);
4277 }
4278 }
4279 Reported = true;
4280 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004281 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004282 }
4283}
4284
Douglas Gregor904eed32008-11-10 20:40:00 +00004285/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4286/// an overloaded function (C++ [over.over]), where @p From is an
4287/// expression with overloaded function type and @p ToType is the type
4288/// we're trying to resolve to. For example:
4289///
4290/// @code
4291/// int f(double);
4292/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00004293///
Douglas Gregor904eed32008-11-10 20:40:00 +00004294/// int (*pfd)(double) = f; // selects f(double)
4295/// @endcode
4296///
4297/// This routine returns the resulting FunctionDecl if it could be
4298/// resolved, and NULL otherwise. When @p Complain is true, this
4299/// routine will emit diagnostics if there is an error.
4300FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00004301Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004302 bool Complain) {
4303 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00004304 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00004305 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00004306 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004307 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00004308 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00004309 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00004310 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00004311 FunctionType = MemTypePtr->getPointeeType();
4312 IsMember = true;
4313 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004314
4315 // We only look at pointers or references to functions.
Douglas Gregor72e771f2009-07-09 17:16:51 +00004316 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor83314aa2009-07-08 20:55:45 +00004317 if (!FunctionType->isFunctionType())
Douglas Gregor904eed32008-11-10 20:40:00 +00004318 return 0;
4319
4320 // Find the actual overloaded function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00004321
Douglas Gregor904eed32008-11-10 20:40:00 +00004322 // C++ [over.over]p1:
4323 // [...] [Note: any redundant set of parentheses surrounding the
4324 // overloaded function name is ignored (5.1). ]
4325 Expr *OvlExpr = From->IgnoreParens();
4326
4327 // C++ [over.over]p1:
4328 // [...] The overloaded function name can be preceded by the &
4329 // operator.
4330 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4331 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4332 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4333 }
4334
Anders Carlsson70534852009-10-20 22:53:47 +00004335 bool HasExplicitTemplateArgs = false;
John McCall833ca992009-10-29 08:12:44 +00004336 const TemplateArgumentLoc *ExplicitTemplateArgs = 0;
Anders Carlsson70534852009-10-20 22:53:47 +00004337 unsigned NumExplicitTemplateArgs = 0;
John McCallba135432009-11-21 08:51:07 +00004338
4339 llvm::SmallVector<NamedDecl*,8> Fns;
Anders Carlsson70534852009-10-20 22:53:47 +00004340
Douglas Gregor904eed32008-11-10 20:40:00 +00004341 // Try to dig out the overloaded function.
John McCallba135432009-11-21 08:51:07 +00004342 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregor83314aa2009-07-08 20:55:45 +00004343 FunctionTemplateDecl *FunctionTemplate = 0;
4344 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
John McCallba135432009-11-21 08:51:07 +00004345 assert(!isa<OverloadedFunctionDecl>(DR->getDecl()));
Douglas Gregor83314aa2009-07-08 20:55:45 +00004346 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00004347 HasExplicitTemplateArgs = DR->hasExplicitTemplateArgumentList();
4348 ExplicitTemplateArgs = DR->getTemplateArgs();
4349 NumExplicitTemplateArgs = DR->getNumTemplateArgs();
John McCallba135432009-11-21 08:51:07 +00004350 } else if (UnresolvedLookupExpr *UL
4351 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4352 Fns.append(UL->decls_begin(), UL->decls_end());
Anders Carlsson6e8f5502009-10-07 22:26:29 +00004353 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(OvlExpr)) {
4354 Ovl = dyn_cast<OverloadedFunctionDecl>(ME->getMemberDecl());
4355 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(ME->getMemberDecl());
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00004356 HasExplicitTemplateArgs = ME->hasExplicitTemplateArgumentList();
4357 ExplicitTemplateArgs = ME->getTemplateArgs();
4358 NumExplicitTemplateArgs = ME->getNumTemplateArgs();
Anders Carlsson70534852009-10-20 22:53:47 +00004359 } else if (TemplateIdRefExpr *TIRE = dyn_cast<TemplateIdRefExpr>(OvlExpr)) {
4360 TemplateName Name = TIRE->getTemplateName();
4361 Ovl = Name.getAsOverloadedFunctionDecl();
4362 FunctionTemplate =
4363 dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4364
4365 HasExplicitTemplateArgs = true;
4366 ExplicitTemplateArgs = TIRE->getTemplateArgs();
4367 NumExplicitTemplateArgs = TIRE->getNumTemplateArgs();
Douglas Gregor83314aa2009-07-08 20:55:45 +00004368 }
Mike Stump1eb44332009-09-09 15:08:12 +00004369
John McCallba135432009-11-21 08:51:07 +00004370 if (Ovl) Fns.append(Ovl->function_begin(), Ovl->function_end());
4371 if (FunctionTemplate) Fns.push_back(FunctionTemplate);
4372
4373 // If we didn't actually find anything, we're done.
4374 if (Fns.empty())
4375 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004376
Douglas Gregor904eed32008-11-10 20:40:00 +00004377 // Look through all of the overloaded functions, searching for one
4378 // whose type matches exactly.
Douglas Gregor00aeb522009-07-08 23:33:52 +00004379 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004380 bool FoundNonTemplateFunction = false;
John McCallba135432009-11-21 08:51:07 +00004381 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4382 E = Fns.end(); I != E; ++I) {
Douglas Gregor904eed32008-11-10 20:40:00 +00004383 // C++ [over.over]p3:
4384 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00004385 // targets of type "pointer-to-function" or "reference-to-function."
4386 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00004387 // type "pointer-to-member-function."
4388 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00004389
Mike Stump1eb44332009-09-09 15:08:12 +00004390 if (FunctionTemplateDecl *FunctionTemplate
John McCallba135432009-11-21 08:51:07 +00004391 = dyn_cast<FunctionTemplateDecl>(*I)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004392 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00004393 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004394 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00004395 // static when converting to member pointer.
4396 if (Method->isStatic() == IsMember)
4397 continue;
4398 } else if (IsMember)
4399 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00004400
Douglas Gregor00aeb522009-07-08 23:33:52 +00004401 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004402 // If the name is a function template, template argument deduction is
4403 // done (14.8.2.2), and if the argument deduction succeeds, the
4404 // resulting template argument list is used to generate a single
4405 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00004406 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004407 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00004408 FunctionDecl *Specialization = 0;
4409 TemplateDeductionInfo Info(Context);
4410 if (TemplateDeductionResult Result
Anders Carlsson70534852009-10-20 22:53:47 +00004411 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
4412 ExplicitTemplateArgs,
4413 NumExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00004414 FunctionType, Specialization, Info)) {
4415 // FIXME: make a note of the failed deduction for diagnostics.
4416 (void)Result;
4417 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004418 // FIXME: If the match isn't exact, shouldn't we just drop this as
4419 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00004420 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00004421 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00004422 Matches.insert(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00004423 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor83314aa2009-07-08 20:55:45 +00004424 }
John McCallba135432009-11-21 08:51:07 +00004425
4426 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00004427 }
Mike Stump1eb44332009-09-09 15:08:12 +00004428
John McCallba135432009-11-21 08:51:07 +00004429 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00004430 // Skip non-static functions when converting to pointer, and static
4431 // when converting to member pointer.
4432 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00004433 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00004434
4435 // If we have explicit template arguments, skip non-templates.
4436 if (HasExplicitTemplateArgs)
4437 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004438 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00004439 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00004440
John McCallba135432009-11-21 08:51:07 +00004441 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*I)) {
Douglas Gregor00aeb522009-07-08 23:33:52 +00004442 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
John McCallba135432009-11-21 08:51:07 +00004443 Matches.insert(cast<FunctionDecl>(FunDecl->getCanonicalDecl()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00004444 FoundNonTemplateFunction = true;
4445 }
Mike Stump1eb44332009-09-09 15:08:12 +00004446 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004447 }
4448
Douglas Gregor00aeb522009-07-08 23:33:52 +00004449 // If there were 0 or 1 matches, we're done.
4450 if (Matches.empty())
4451 return 0;
Sebastian Redl07ab2022009-10-17 21:12:09 +00004452 else if (Matches.size() == 1) {
4453 FunctionDecl *Result = *Matches.begin();
4454 MarkDeclarationReferenced(From->getLocStart(), Result);
4455 return Result;
4456 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00004457
4458 // C++ [over.over]p4:
4459 // If more than one function is selected, [...]
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004460 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregor312a2022009-09-26 03:56:17 +00004461 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004462 // [...] and any given function template specialization F1 is
4463 // eliminated if the set contains a second function template
4464 // specialization whose function template is more specialized
4465 // than the function template of F1 according to the partial
4466 // ordering rules of 14.5.5.2.
4467
4468 // The algorithm specified above is quadratic. We instead use a
4469 // two-pass algorithm (similar to the one used to identify the
4470 // best viable function in an overload set) that identifies the
4471 // best function template (if it exists).
Sebastian Redl07ab2022009-10-17 21:12:09 +00004472 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregor312a2022009-09-26 03:56:17 +00004473 Matches.end());
Sebastian Redl07ab2022009-10-17 21:12:09 +00004474 FunctionDecl *Result =
4475 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4476 TPOC_Other, From->getLocStart(),
4477 PDiag(),
4478 PDiag(diag::err_addr_ovl_ambiguous)
4479 << TemplateMatches[0]->getDeclName(),
4480 PDiag(diag::err_ovl_template_candidate));
4481 MarkDeclarationReferenced(From->getLocStart(), Result);
4482 return Result;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004483 }
Mike Stump1eb44332009-09-09 15:08:12 +00004484
Douglas Gregor312a2022009-09-26 03:56:17 +00004485 // [...] any function template specializations in the set are
4486 // eliminated if the set also contains a non-template function, [...]
4487 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4488 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4489 if ((*M)->getPrimaryTemplate() == 0)
4490 RemainingMatches.push_back(*M);
4491
Mike Stump1eb44332009-09-09 15:08:12 +00004492 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00004493 // selected function.
Sebastian Redl07ab2022009-10-17 21:12:09 +00004494 if (RemainingMatches.size() == 1) {
4495 FunctionDecl *Result = RemainingMatches.front();
4496 MarkDeclarationReferenced(From->getLocStart(), Result);
4497 return Result;
4498 }
Mike Stump1eb44332009-09-09 15:08:12 +00004499
Douglas Gregor00aeb522009-07-08 23:33:52 +00004500 // FIXME: We should probably return the same thing that BestViableFunction
4501 // returns (even if we issue the diagnostics here).
4502 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4503 << RemainingMatches[0]->getDeclName();
4504 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4505 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregor904eed32008-11-10 20:40:00 +00004506 return 0;
4507}
4508
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004509/// \brief Add a single candidate to the overload set.
4510static void AddOverloadedCallCandidate(Sema &S,
John McCallba135432009-11-21 08:51:07 +00004511 NamedDecl *Callee,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004512 bool HasExplicitTemplateArgs,
John McCall833ca992009-10-29 08:12:44 +00004513 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004514 unsigned NumExplicitTemplateArgs,
4515 Expr **Args, unsigned NumArgs,
4516 OverloadCandidateSet &CandidateSet,
4517 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00004518 if (isa<UsingShadowDecl>(Callee))
4519 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
4520
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004521 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
4522 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
4523 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4524 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004525 return;
John McCallba135432009-11-21 08:51:07 +00004526 }
4527
4528 if (FunctionTemplateDecl *FuncTemplate
4529 = dyn_cast<FunctionTemplateDecl>(Callee)) {
4530 S.AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4531 ExplicitTemplateArgs,
4532 NumExplicitTemplateArgs,
4533 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00004534 return;
4535 }
4536
4537 assert(false && "unhandled case in overloaded call candidate");
4538
4539 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004540}
4541
4542/// \brief Add the overload candidates named by callee and/or found by argument
4543/// dependent lookup to the given overload set.
John McCallba135432009-11-21 08:51:07 +00004544void Sema::AddOverloadedCallCandidates(llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004545 DeclarationName &UnqualifiedName,
John McCalld2ede7d2009-11-21 09:38:42 +00004546 bool ArgumentDependentLookup,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004547 bool HasExplicitTemplateArgs,
John McCall833ca992009-10-29 08:12:44 +00004548 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004549 unsigned NumExplicitTemplateArgs,
4550 Expr **Args, unsigned NumArgs,
4551 OverloadCandidateSet &CandidateSet,
4552 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00004553
4554#ifndef NDEBUG
4555 // Verify that ArgumentDependentLookup is consistent with the rules
4556 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004557 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004558 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4559 // and let Y be the lookup set produced by argument dependent
4560 // lookup (defined as follows). If X contains
4561 //
4562 // -- a declaration of a class member, or
4563 //
4564 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00004565 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004566 //
4567 // -- a declaration that is neither a function or a function
4568 // template
4569 //
4570 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00004571
4572 if (ArgumentDependentLookup) {
4573 for (unsigned I = 0; I < Fns.size(); ++I) {
4574 assert(!Fns[I]->getDeclContext()->isRecord());
4575 assert(isa<UsingShadowDecl>(Fns[I]) ||
4576 !Fns[I]->getDeclContext()->isFunctionOrMethod());
4577 assert(Fns[I]->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
4578 }
4579 }
4580#endif
4581
4582 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4583 E = Fns.end(); I != E; ++I)
John McCalld2ede7d2009-11-21 09:38:42 +00004584 AddOverloadedCallCandidate(*this, *I, HasExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004585 ExplicitTemplateArgs, NumExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00004586 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004587 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00004588
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004589 if (ArgumentDependentLookup)
4590 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
4591 HasExplicitTemplateArgs,
4592 ExplicitTemplateArgs,
4593 NumExplicitTemplateArgs,
4594 CandidateSet,
4595 PartialOverloading);
4596}
4597
Douglas Gregorf6b89692008-11-26 05:54:23 +00004598/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00004599/// (which eventually refers to the declaration Func) and the call
4600/// arguments Args/NumArgs, attempt to resolve the function call down
4601/// to a specific function. If overload resolution succeeds, returns
4602/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00004603/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00004604/// arguments and Fn, and returns NULL.
John McCallba135432009-11-21 08:51:07 +00004605FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn,
4606 llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregor17330012009-02-04 15:01:18 +00004607 DeclarationName UnqualifiedName,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004608 bool HasExplicitTemplateArgs,
John McCall833ca992009-10-29 08:12:44 +00004609 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004610 unsigned NumExplicitTemplateArgs,
Douglas Gregor0a396682008-11-26 06:01:48 +00004611 SourceLocation LParenLoc,
4612 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00004613 SourceLocation *CommaLocs,
Douglas Gregorfa047642009-02-04 00:32:51 +00004614 SourceLocation RParenLoc,
John McCalld2ede7d2009-11-21 09:38:42 +00004615 bool ArgumentDependentLookup) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00004616 OverloadCandidateSet CandidateSet;
Douglas Gregor17330012009-02-04 15:01:18 +00004617
4618 // Add the functions denoted by Callee to the set of candidate
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004619 // functions.
John McCallba135432009-11-21 08:51:07 +00004620 AddOverloadedCallCandidates(Fns, UnqualifiedName, ArgumentDependentLookup,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004621 HasExplicitTemplateArgs, ExplicitTemplateArgs,
4622 NumExplicitTemplateArgs, Args, NumArgs,
4623 CandidateSet);
Douglas Gregorf6b89692008-11-26 05:54:23 +00004624 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004625 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00004626 case OR_Success:
4627 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00004628
4629 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00004630 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00004631 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00004632 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00004633 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4634 break;
4635
4636 case OR_Ambiguous:
4637 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor17330012009-02-04 15:01:18 +00004638 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00004639 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4640 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004641
4642 case OR_Deleted:
4643 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4644 << Best->Function->isDeleted()
4645 << UnqualifiedName
4646 << Fn->getSourceRange();
4647 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4648 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00004649 }
4650
4651 // Overload resolution failed. Destroy all of the subexpressions and
4652 // return NULL.
4653 Fn->Destroy(Context);
4654 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4655 Args[Arg]->Destroy(Context);
4656 return 0;
4657}
4658
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004659/// \brief Create a unary operation that may resolve to an overloaded
4660/// operator.
4661///
4662/// \param OpLoc The location of the operator itself (e.g., '*').
4663///
4664/// \param OpcIn The UnaryOperator::Opcode that describes this
4665/// operator.
4666///
4667/// \param Functions The set of non-member functions that will be
4668/// considered by overload resolution. The caller needs to build this
4669/// set based on the context using, e.g.,
4670/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4671/// set should not contain any member functions; those will be added
4672/// by CreateOverloadedUnaryOp().
4673///
4674/// \param input The input argument.
4675Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4676 unsigned OpcIn,
4677 FunctionSet &Functions,
Mike Stump1eb44332009-09-09 15:08:12 +00004678 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004679 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4680 Expr *Input = (Expr *)input.get();
4681
4682 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4683 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4684 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4685
4686 Expr *Args[2] = { Input, 0 };
4687 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004688
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004689 // For post-increment and post-decrement, add the implicit '0' as
4690 // the second argument, so that we know this is a post-increment or
4691 // post-decrement.
4692 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4693 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00004694 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004695 SourceLocation());
4696 NumArgs = 2;
4697 }
4698
4699 if (Input->isTypeDependent()) {
John McCallba135432009-11-21 08:51:07 +00004700 UnresolvedLookupExpr *Fn
4701 = UnresolvedLookupExpr::Create(Context, 0, SourceRange(), OpName, OpLoc,
4702 /*ADL*/ true);
Mike Stump1eb44332009-09-09 15:08:12 +00004703 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004704 FuncEnd = Functions.end();
4705 Func != FuncEnd; ++Func)
John McCallba135432009-11-21 08:51:07 +00004706 Fn->addDecl(*Func);
Mike Stump1eb44332009-09-09 15:08:12 +00004707
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004708 input.release();
4709 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4710 &Args[0], NumArgs,
4711 Context.DependentTy,
4712 OpLoc));
4713 }
4714
4715 // Build an empty overload set.
4716 OverloadCandidateSet CandidateSet;
4717
4718 // Add the candidates from the given function set.
4719 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4720
4721 // Add operator candidates that are member functions.
4722 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4723
4724 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00004725 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004726
4727 // Perform overload resolution.
4728 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004729 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004730 case OR_Success: {
4731 // We found a built-in operator or an overloaded operator.
4732 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00004733
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004734 if (FnDecl) {
4735 // We matched an overloaded operator. Build a call to that
4736 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00004737
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004738 // Convert the arguments.
4739 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4740 if (PerformObjectArgumentInitialization(Input, Method))
4741 return ExprError();
4742 } else {
4743 // Convert the arguments.
4744 if (PerformCopyInitialization(Input,
4745 FnDecl->getParamDecl(0)->getType(),
4746 "passing"))
4747 return ExprError();
4748 }
4749
4750 // Determine the result type
Anders Carlsson26a2a072009-10-13 21:19:37 +00004751 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00004752
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004753 // Build the actual expression node.
4754 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4755 SourceLocation());
4756 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004757
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004758 input.release();
Eli Friedman4c3b8962009-11-18 03:58:17 +00004759 Args[0] = Input;
Anders Carlsson26a2a072009-10-13 21:19:37 +00004760 ExprOwningPtr<CallExpr> TheCall(this,
4761 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman4c3b8962009-11-18 03:58:17 +00004762 Args, NumArgs, ResultTy, OpLoc));
Anders Carlsson26a2a072009-10-13 21:19:37 +00004763
4764 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4765 FnDecl))
4766 return ExprError();
4767
4768 return MaybeBindToTemporary(TheCall.release());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004769 } else {
4770 // We matched a built-in operator. Convert the arguments, then
4771 // break out so that we will build the appropriate built-in
4772 // operator node.
4773 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4774 Best->Conversions[0], "passing"))
4775 return ExprError();
4776
4777 break;
4778 }
4779 }
4780
4781 case OR_No_Viable_Function:
4782 // No viable function; fall through to handling this as a
4783 // built-in operator, which will produce an error message for us.
4784 break;
4785
4786 case OR_Ambiguous:
4787 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4788 << UnaryOperator::getOpcodeStr(Opc)
4789 << Input->getSourceRange();
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004790 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4791 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004792 return ExprError();
4793
4794 case OR_Deleted:
4795 Diag(OpLoc, diag::err_ovl_deleted_oper)
4796 << Best->Function->isDeleted()
4797 << UnaryOperator::getOpcodeStr(Opc)
4798 << Input->getSourceRange();
4799 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4800 return ExprError();
4801 }
4802
4803 // Either we found no viable overloaded operator or we matched a
4804 // built-in operator. In either case, fall through to trying to
4805 // build a built-in operation.
4806 input.release();
4807 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4808}
4809
Douglas Gregor063daf62009-03-13 18:40:31 +00004810/// \brief Create a binary operation that may resolve to an overloaded
4811/// operator.
4812///
4813/// \param OpLoc The location of the operator itself (e.g., '+').
4814///
4815/// \param OpcIn The BinaryOperator::Opcode that describes this
4816/// operator.
4817///
4818/// \param Functions The set of non-member functions that will be
4819/// considered by overload resolution. The caller needs to build this
4820/// set based on the context using, e.g.,
4821/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4822/// set should not contain any member functions; those will be added
4823/// by CreateOverloadedBinOp().
4824///
4825/// \param LHS Left-hand argument.
4826/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00004827Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00004828Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004829 unsigned OpcIn,
Douglas Gregor063daf62009-03-13 18:40:31 +00004830 FunctionSet &Functions,
4831 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00004832 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004833 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00004834
4835 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4836 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4837 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4838
4839 // If either side is type-dependent, create an appropriate dependent
4840 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004841 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00004842 if (Functions.empty()) {
4843 // If there are no functions to store, just build a dependent
4844 // BinaryOperator or CompoundAssignment.
4845 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
4846 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
4847 Context.DependentTy, OpLoc));
4848
4849 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
4850 Context.DependentTy,
4851 Context.DependentTy,
4852 Context.DependentTy,
4853 OpLoc));
4854 }
4855
John McCallba135432009-11-21 08:51:07 +00004856 UnresolvedLookupExpr *Fn
4857 = UnresolvedLookupExpr::Create(Context, 0, SourceRange(), OpName, OpLoc,
4858 /* ADL */ true);
4859
Mike Stump1eb44332009-09-09 15:08:12 +00004860 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004861 FuncEnd = Functions.end();
4862 Func != FuncEnd; ++Func)
John McCallba135432009-11-21 08:51:07 +00004863 Fn->addDecl(*Func);
Mike Stump1eb44332009-09-09 15:08:12 +00004864
Douglas Gregor063daf62009-03-13 18:40:31 +00004865 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00004866 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00004867 Context.DependentTy,
4868 OpLoc));
4869 }
4870
4871 // If this is the .* operator, which is not overloadable, just
4872 // create a built-in binary operator.
4873 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004874 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00004875
Sebastian Redl275c2b42009-11-18 23:10:33 +00004876 // If this is the assignment operator, we only perform overload resolution
4877 // if the left-hand side is a class or enumeration type. This is actually
4878 // a hack. The standard requires that we do overload resolution between the
4879 // various built-in candidates, but as DR507 points out, this can lead to
4880 // problems. So we do it this way, which pretty much follows what GCC does.
4881 // Note that we go the traditional code path for compound assignment forms.
4882 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004883 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00004884
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004885 // Build an empty overload set.
4886 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00004887
4888 // Add the candidates from the given function set.
4889 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4890
4891 // Add operator candidates that are member functions.
4892 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4893
4894 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00004895 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00004896
4897 // Perform overload resolution.
4898 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004899 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004900 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00004901 // We found a built-in operator or an overloaded operator.
4902 FunctionDecl *FnDecl = Best->Function;
4903
4904 if (FnDecl) {
4905 // We matched an overloaded operator. Build a call to that
4906 // operator.
4907
4908 // Convert the arguments.
4909 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004910 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4911 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004912 "passing"))
4913 return ExprError();
4914 } else {
4915 // Convert the arguments.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004916 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004917 "passing") ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004918 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004919 "passing"))
4920 return ExprError();
4921 }
4922
4923 // Determine the result type
4924 QualType ResultTy
John McCall183700f2009-09-21 23:43:11 +00004925 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor063daf62009-03-13 18:40:31 +00004926 ResultTy = ResultTy.getNonReferenceType();
4927
4928 // Build the actual expression node.
4929 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00004930 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00004931 UsualUnaryConversions(FnExpr);
4932
Anders Carlsson15ea3782009-10-13 22:43:21 +00004933 ExprOwningPtr<CXXOperatorCallExpr>
4934 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4935 Args, 2, ResultTy,
4936 OpLoc));
4937
4938 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4939 FnDecl))
4940 return ExprError();
4941
4942 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor063daf62009-03-13 18:40:31 +00004943 } else {
4944 // We matched a built-in operator. Convert the arguments, then
4945 // break out so that we will build the appropriate built-in
4946 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004947 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor063daf62009-03-13 18:40:31 +00004948 Best->Conversions[0], "passing") ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004949 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor063daf62009-03-13 18:40:31 +00004950 Best->Conversions[1], "passing"))
4951 return ExprError();
4952
4953 break;
4954 }
4955 }
4956
Douglas Gregor33074752009-09-30 21:46:01 +00004957 case OR_No_Viable_Function: {
4958 // C++ [over.match.oper]p9:
4959 // If the operator is the operator , [...] and there are no
4960 // viable functions, then the operator is assumed to be the
4961 // built-in operator and interpreted according to clause 5.
4962 if (Opc == BinaryOperator::Comma)
4963 break;
4964
Sebastian Redl8593c782009-05-21 11:50:50 +00004965 // For class as left operand for assignment or compound assigment operator
4966 // do not fall through to handling in built-in, but report that no overloaded
4967 // assignment operator found
Douglas Gregor33074752009-09-30 21:46:01 +00004968 OwningExprResult Result = ExprError();
4969 if (Args[0]->getType()->isRecordType() &&
4970 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00004971 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4972 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004973 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00004974 } else {
4975 // No viable function; try to create a built-in operation, which will
4976 // produce an error. Then, show the non-viable candidates.
4977 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00004978 }
Douglas Gregor33074752009-09-30 21:46:01 +00004979 assert(Result.isInvalid() &&
4980 "C++ binary operator overloading is missing candidates!");
4981 if (Result.isInvalid())
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004982 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
4983 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00004984 return move(Result);
4985 }
Douglas Gregor063daf62009-03-13 18:40:31 +00004986
4987 case OR_Ambiguous:
4988 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4989 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004990 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004991 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4992 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00004993 return ExprError();
4994
4995 case OR_Deleted:
4996 Diag(OpLoc, diag::err_ovl_deleted_oper)
4997 << Best->Function->isDeleted()
4998 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004999 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor063daf62009-03-13 18:40:31 +00005000 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5001 return ExprError();
5002 }
5003
Douglas Gregor33074752009-09-30 21:46:01 +00005004 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005005 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005006}
5007
Sebastian Redlf322ed62009-10-29 20:17:01 +00005008Action::OwningExprResult
5009Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5010 SourceLocation RLoc,
5011 ExprArg Base, ExprArg Idx) {
5012 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5013 static_cast<Expr*>(Idx.get()) };
5014 DeclarationName OpName =
5015 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5016
5017 // If either side is type-dependent, create an appropriate dependent
5018 // expression.
5019 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5020
John McCallba135432009-11-21 08:51:07 +00005021 UnresolvedLookupExpr *Fn
5022 = UnresolvedLookupExpr::Create(Context, 0, SourceRange(), OpName, LLoc,
5023 /*ADL*/ true);
5024 // Can't add an actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00005025
5026 Base.release();
5027 Idx.release();
5028 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5029 Args, 2,
5030 Context.DependentTy,
5031 RLoc));
5032 }
5033
5034 // Build an empty overload set.
5035 OverloadCandidateSet CandidateSet;
5036
5037 // Subscript can only be overloaded as a member function.
5038
5039 // Add operator candidates that are member functions.
5040 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5041
5042 // Add builtin operator candidates.
5043 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5044
5045 // Perform overload resolution.
5046 OverloadCandidateSet::iterator Best;
5047 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5048 case OR_Success: {
5049 // We found a built-in operator or an overloaded operator.
5050 FunctionDecl *FnDecl = Best->Function;
5051
5052 if (FnDecl) {
5053 // We matched an overloaded operator. Build a call to that
5054 // operator.
5055
5056 // Convert the arguments.
5057 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5058 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5059 PerformCopyInitialization(Args[1],
5060 FnDecl->getParamDecl(0)->getType(),
5061 "passing"))
5062 return ExprError();
5063
5064 // Determine the result type
5065 QualType ResultTy
5066 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5067 ResultTy = ResultTy.getNonReferenceType();
5068
5069 // Build the actual expression node.
5070 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5071 LLoc);
5072 UsualUnaryConversions(FnExpr);
5073
5074 Base.release();
5075 Idx.release();
5076 ExprOwningPtr<CXXOperatorCallExpr>
5077 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5078 FnExpr, Args, 2,
5079 ResultTy, RLoc));
5080
5081 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5082 FnDecl))
5083 return ExprError();
5084
5085 return MaybeBindToTemporary(TheCall.release());
5086 } else {
5087 // We matched a built-in operator. Convert the arguments, then
5088 // break out so that we will build the appropriate built-in
5089 // operator node.
5090 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
5091 Best->Conversions[0], "passing") ||
5092 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
5093 Best->Conversions[1], "passing"))
5094 return ExprError();
5095
5096 break;
5097 }
5098 }
5099
5100 case OR_No_Viable_Function: {
5101 // No viable function; try to create a built-in operation, which will
5102 // produce an error. Then, show the non-viable candidates.
5103 OwningExprResult Result =
5104 CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
5105 assert(Result.isInvalid() &&
5106 "C++ subscript operator overloading is missing candidates!");
5107 if (Result.isInvalid())
5108 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5109 "[]", LLoc);
5110 return move(Result);
5111 }
5112
5113 case OR_Ambiguous:
5114 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5115 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5116 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5117 "[]", LLoc);
5118 return ExprError();
5119
5120 case OR_Deleted:
5121 Diag(LLoc, diag::err_ovl_deleted_oper)
5122 << Best->Function->isDeleted() << "[]"
5123 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5124 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5125 return ExprError();
5126 }
5127
5128 // We matched a built-in operator; build it.
5129 Base.release();
5130 Idx.release();
5131 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5132 Owned(Args[1]), RLoc);
5133}
5134
Douglas Gregor88a35142008-12-22 05:46:06 +00005135/// BuildCallToMemberFunction - Build a call to a member
5136/// function. MemExpr is the expression that refers to the member
5137/// function (and includes the object parameter), Args/NumArgs are the
5138/// arguments to the function call (not including the object
5139/// parameter). The caller needs to validate that the member
5140/// expression refers to a member function or an overloaded member
5141/// function.
5142Sema::ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00005143Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5144 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00005145 unsigned NumArgs, SourceLocation *CommaLocs,
5146 SourceLocation RParenLoc) {
5147 // Dig out the member expression. This holds both the object
5148 // argument and the member function we're referring to.
5149 MemberExpr *MemExpr = 0;
5150 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
5151 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
5152 else
5153 MemExpr = dyn_cast<MemberExpr>(MemExprE);
5154 assert(MemExpr && "Building member call without member expression");
5155
5156 // Extract the object argument.
5157 Expr *ObjectArg = MemExpr->getBase();
Anders Carlssona552f7c2009-05-01 18:34:30 +00005158
Douglas Gregor88a35142008-12-22 05:46:06 +00005159 CXXMethodDecl *Method = 0;
Douglas Gregor6b906862009-08-21 00:16:32 +00005160 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
5161 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005162 // Add overload candidates
5163 OverloadCandidateSet CandidateSet;
Douglas Gregor6b906862009-08-21 00:16:32 +00005164 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00005165
Douglas Gregordec06662009-08-21 18:42:58 +00005166 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
5167 Func != FuncEnd; ++Func) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005168 if ((Method = dyn_cast<CXXMethodDecl>(*Func))) {
5169 // If explicit template arguments were provided, we can't call a
5170 // non-template member function.
5171 if (MemExpr->hasExplicitTemplateArgumentList())
5172 continue;
5173
Mike Stump1eb44332009-09-09 15:08:12 +00005174 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +00005175 /*SuppressUserConversions=*/false);
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005176 } else
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00005177 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
5178 MemExpr->hasExplicitTemplateArgumentList(),
5179 MemExpr->getTemplateArgs(),
5180 MemExpr->getNumTemplateArgs(),
5181 ObjectArg, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00005182 CandidateSet,
5183 /*SuppressUsedConversions=*/false);
5184 }
Mike Stump1eb44332009-09-09 15:08:12 +00005185
Douglas Gregor88a35142008-12-22 05:46:06 +00005186 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005187 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005188 case OR_Success:
5189 Method = cast<CXXMethodDecl>(Best->Function);
5190 break;
5191
5192 case OR_No_Viable_Function:
Mike Stump1eb44332009-09-09 15:08:12 +00005193 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor88a35142008-12-22 05:46:06 +00005194 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00005195 << DeclName << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00005196 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5197 // FIXME: Leaking incoming expressions!
5198 return true;
5199
5200 case OR_Ambiguous:
Mike Stump1eb44332009-09-09 15:08:12 +00005201 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor88a35142008-12-22 05:46:06 +00005202 diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00005203 << DeclName << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00005204 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5205 // FIXME: Leaking incoming expressions!
5206 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005207
5208 case OR_Deleted:
Mike Stump1eb44332009-09-09 15:08:12 +00005209 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005210 diag::err_ovl_deleted_member_call)
5211 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00005212 << DeclName << MemExprE->getSourceRange();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005213 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5214 // FIXME: Leaking incoming expressions!
5215 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005216 }
5217
Douglas Gregor699ee522009-11-20 19:42:02 +00005218 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
5219 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
5220 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
5221 else
5222 MemExpr = dyn_cast<MemberExpr>(MemExprE);
5223
Douglas Gregor88a35142008-12-22 05:46:06 +00005224 } else {
5225 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5226 }
5227
5228 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00005229 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek668bf912009-02-09 20:51:47 +00005230 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00005231 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00005232 Method->getResultType().getNonReferenceType(),
5233 RParenLoc));
5234
Anders Carlssoneed3e692009-10-10 00:06:20 +00005235 // Check for a valid return type.
5236 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5237 TheCall.get(), Method))
5238 return true;
5239
Douglas Gregor88a35142008-12-22 05:46:06 +00005240 // Convert the object argument (for a non-static member function call).
Mike Stump1eb44332009-09-09 15:08:12 +00005241 if (!Method->isStatic() &&
Douglas Gregor88a35142008-12-22 05:46:06 +00005242 PerformObjectArgumentInitialization(ObjectArg, Method))
5243 return true;
5244 MemExpr->setBase(ObjectArg);
5245
5246 // Convert the rest of the arguments
Douglas Gregor72564e72009-02-26 23:50:07 +00005247 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00005248 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00005249 RParenLoc))
5250 return true;
5251
Anders Carlssond406bf02009-08-16 01:56:34 +00005252 if (CheckFunctionCall(Method, TheCall.get()))
5253 return true;
Anders Carlsson6f680272009-08-16 03:42:12 +00005254
5255 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor88a35142008-12-22 05:46:06 +00005256}
5257
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005258/// BuildCallToObjectOfClassType - Build a call to an object of class
5259/// type (C++ [over.call.object]), which can end up invoking an
5260/// overloaded function call operator (@c operator()) or performing a
5261/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00005262Sema::ExprResult
5263Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00005264 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005265 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00005266 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005267 SourceLocation RParenLoc) {
5268 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00005269 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005270
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005271 // C++ [over.call.object]p1:
5272 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00005273 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005274 // candidate functions includes at least the function call
5275 // operators of T. The function call operators of T are obtained by
5276 // ordinary lookup of the name operator() in the context of
5277 // (E).operator().
5278 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00005279 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00005280
5281 if (RequireCompleteType(LParenLoc, Object->getType(),
5282 PartialDiagnostic(diag::err_incomplete_object_call)
5283 << Object->getSourceRange()))
5284 return true;
5285
John McCalla24dc2e2009-11-17 02:14:36 +00005286 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5287 LookupQualifiedName(R, Record->getDecl());
5288 R.suppressDiagnostics();
5289
Douglas Gregor593564b2009-11-15 07:48:03 +00005290 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00005291 Oper != OperEnd; ++Oper) {
John McCall314be4e2009-11-17 07:50:12 +00005292 AddMethodCandidate(*Oper, Object, Args, NumArgs, CandidateSet,
5293 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00005294 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00005295
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005296 // C++ [over.call.object]p2:
5297 // In addition, for each conversion function declared in T of the
5298 // form
5299 //
5300 // operator conversion-type-id () cv-qualifier;
5301 //
5302 // where cv-qualifier is the same cv-qualification as, or a
5303 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00005304 // denotes the type "pointer to function of (P1,...,Pn) returning
5305 // R", or the type "reference to pointer to function of
5306 // (P1,...,Pn) returning R", or the type "reference to function
5307 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005308 // is also considered as a candidate function. Similarly,
5309 // surrogate call functions are added to the set of candidate
5310 // functions for each conversion function declared in an
5311 // accessible base class provided the function is not hidden
5312 // within T by another intervening declaration.
Douglas Gregor4a27d702009-10-21 06:18:39 +00005313 // FIXME: Look in base classes for more conversion operators!
John McCallba135432009-11-21 08:51:07 +00005314 const UnresolvedSet *Conversions
Douglas Gregor4a27d702009-10-21 06:18:39 +00005315 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00005316 for (UnresolvedSet::iterator I = Conversions->begin(),
5317 E = Conversions->end(); I != E; ++I) {
Douglas Gregor4a27d702009-10-21 06:18:39 +00005318 // Skip over templated conversion functions; they aren't
5319 // surrogates.
John McCallba135432009-11-21 08:51:07 +00005320 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor4a27d702009-10-21 06:18:39 +00005321 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005322
John McCallba135432009-11-21 08:51:07 +00005323 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
5324
Douglas Gregor4a27d702009-10-21 06:18:39 +00005325 // Strip the reference type (if any) and then the pointer type (if
5326 // any) to get down to what might be a function type.
5327 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5328 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5329 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005330
Douglas Gregor4a27d702009-10-21 06:18:39 +00005331 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
5332 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005333 }
Mike Stump1eb44332009-09-09 15:08:12 +00005334
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005335 // Perform overload resolution.
5336 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005337 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005338 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005339 // Overload resolution succeeded; we'll build the appropriate call
5340 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005341 break;
5342
5343 case OR_No_Viable_Function:
Mike Stump1eb44332009-09-09 15:08:12 +00005344 Diag(Object->getSourceRange().getBegin(),
Sebastian Redle4c452c2008-11-22 13:44:36 +00005345 diag::err_ovl_no_viable_object_call)
Chris Lattner4330d652009-02-17 07:29:20 +00005346 << Object->getType() << Object->getSourceRange();
Sebastian Redle4c452c2008-11-22 13:44:36 +00005347 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005348 break;
5349
5350 case OR_Ambiguous:
5351 Diag(Object->getSourceRange().getBegin(),
5352 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00005353 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005354 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5355 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005356
5357 case OR_Deleted:
5358 Diag(Object->getSourceRange().getBegin(),
5359 diag::err_ovl_deleted_object_call)
5360 << Best->Function->isDeleted()
5361 << Object->getType() << Object->getSourceRange();
5362 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5363 break;
Mike Stump1eb44332009-09-09 15:08:12 +00005364 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005365
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005366 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005367 // We had an error; delete all of the subexpressions and return
5368 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00005369 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005370 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00005371 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005372 return true;
5373 }
5374
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005375 if (Best->Function == 0) {
5376 // Since there is no function declaration, this is one of the
5377 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00005378 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005379 = cast<CXXConversionDecl>(
5380 Best->Conversions[0].UserDefined.ConversionFunction);
5381
5382 // We selected one of the surrogate functions that converts the
5383 // object parameter to a function pointer. Perform the conversion
5384 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00005385
5386 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00005387 // and then call it.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00005388 CXXMemberCallExpr *CE =
Fariborz Jahanianb7400232009-09-28 23:23:40 +00005389 BuildCXXMemberCallExpr(Object, Conv);
5390
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00005391 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00005392 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5393 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005394 }
5395
5396 // We found an overloaded operator(). Build a CXXOperatorCallExpr
5397 // that calls this method, using Object for the implicit object
5398 // parameter and passing along the remaining arguments.
5399 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00005400 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005401
5402 unsigned NumArgsInProto = Proto->getNumArgs();
5403 unsigned NumArgsToCheck = NumArgs;
5404
5405 // Build the full argument list for the method call (the
5406 // implicit object parameter is placed at the beginning of the
5407 // list).
5408 Expr **MethodArgs;
5409 if (NumArgs < NumArgsInProto) {
5410 NumArgsToCheck = NumArgsInProto;
5411 MethodArgs = new Expr*[NumArgsInProto + 1];
5412 } else {
5413 MethodArgs = new Expr*[NumArgs + 1];
5414 }
5415 MethodArgs[0] = Object;
5416 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5417 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00005418
5419 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00005420 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005421 UsualUnaryConversions(NewFn);
5422
5423 // Once we've built TheCall, all of the expressions are properly
5424 // owned.
5425 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00005426 ExprOwningPtr<CXXOperatorCallExpr>
5427 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00005428 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005429 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005430 delete [] MethodArgs;
5431
Anders Carlsson07d68f12009-10-13 21:49:31 +00005432 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5433 Method))
5434 return true;
5435
Douglas Gregor518fda12009-01-13 05:10:00 +00005436 // We may have default arguments. If so, we need to allocate more
5437 // slots in the call for them.
5438 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00005439 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00005440 else if (NumArgs > NumArgsInProto)
5441 NumArgsToCheck = NumArgsInProto;
5442
Chris Lattner312531a2009-04-12 08:11:20 +00005443 bool IsError = false;
5444
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005445 // Initialize the implicit object parameter.
Chris Lattner312531a2009-04-12 08:11:20 +00005446 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005447 TheCall->setArg(0, Object);
5448
Chris Lattner312531a2009-04-12 08:11:20 +00005449
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005450 // Check the argument types.
5451 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005452 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00005453 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005454 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00005455
Douglas Gregor518fda12009-01-13 05:10:00 +00005456 // Pass the argument.
5457 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner312531a2009-04-12 08:11:20 +00005458 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor518fda12009-01-13 05:10:00 +00005459 } else {
Douglas Gregord47c47d2009-11-09 19:27:57 +00005460 OwningExprResult DefArg
5461 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
5462 if (DefArg.isInvalid()) {
5463 IsError = true;
5464 break;
5465 }
5466
5467 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00005468 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005469
5470 TheCall->setArg(i + 1, Arg);
5471 }
5472
5473 // If this is a variadic call, handle args passed through "...".
5474 if (Proto->isVariadic()) {
5475 // Promote the arguments (C99 6.5.2.2p7).
5476 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5477 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00005478 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005479 TheCall->setArg(i + 1, Arg);
5480 }
5481 }
5482
Chris Lattner312531a2009-04-12 08:11:20 +00005483 if (IsError) return true;
5484
Anders Carlssond406bf02009-08-16 01:56:34 +00005485 if (CheckFunctionCall(Method, TheCall.get()))
5486 return true;
5487
Anders Carlssona303f9e2009-08-16 03:53:54 +00005488 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005489}
5490
Douglas Gregor8ba10742008-11-20 16:27:02 +00005491/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00005492/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00005493/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005494Sema::OwningExprResult
5495Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5496 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00005497 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00005498
Douglas Gregor8ba10742008-11-20 16:27:02 +00005499 // C++ [over.ref]p1:
5500 //
5501 // [...] An expression x->m is interpreted as (x.operator->())->m
5502 // for a class object x of type T if T::operator->() exists and if
5503 // the operator is selected as the best match function by the
5504 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00005505 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5506 OverloadCandidateSet CandidateSet;
Ted Kremenek6217b802009-07-29 21:53:49 +00005507 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005508
Eli Friedmanf43fb722009-11-18 01:28:03 +00005509 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
5510 PDiag(diag::err_typecheck_incomplete_tag)
5511 << Base->getSourceRange()))
5512 return ExprError();
5513
John McCalla24dc2e2009-11-17 02:14:36 +00005514 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
5515 LookupQualifiedName(R, BaseRecord->getDecl());
5516 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00005517
5518 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
5519 Oper != OperEnd; ++Oper)
Douglas Gregor3fc749d2008-12-23 00:26:44 +00005520 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00005521 /*SuppressUserConversions=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00005522
5523 // Perform overload resolution.
5524 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005525 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00005526 case OR_Success:
5527 // Overload resolution succeeded; we'll build the call below.
5528 break;
5529
5530 case OR_No_Viable_Function:
5531 if (CandidateSet.empty())
5532 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005533 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005534 else
5535 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005536 << "operator->" << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005537 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005538 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005539
5540 case OR_Ambiguous:
5541 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00005542 << "->" << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005543 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005544 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005545
5546 case OR_Deleted:
5547 Diag(OpLoc, diag::err_ovl_deleted_oper)
5548 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00005549 << "->" << Base->getSourceRange();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005550 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005551 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005552 }
5553
5554 // Convert the object parameter.
5555 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00005556 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005557 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00005558
5559 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005560 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005561
5562 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00005563 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5564 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00005565 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00005566
5567 QualType ResultTy = Method->getResultType().getNonReferenceType();
5568 ExprOwningPtr<CXXOperatorCallExpr>
5569 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
5570 &Base, 1, ResultTy, OpLoc));
5571
5572 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
5573 Method))
5574 return ExprError();
5575 return move(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00005576}
5577
Douglas Gregor904eed32008-11-10 20:40:00 +00005578/// FixOverloadedFunctionReference - E is an expression that refers to
5579/// a C++ overloaded function (possibly with some parentheses and
5580/// perhaps a '&' around it). We have resolved the overloaded function
5581/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00005582/// refer (possibly indirectly) to Fn. Returns the new expr.
5583Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005584 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor699ee522009-11-20 19:42:02 +00005585 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5586 if (SubExpr == PE->getSubExpr())
5587 return PE->Retain();
5588
5589 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
5590 }
5591
5592 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5593 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00005594 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00005595 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00005596 "Implicit cast type cannot be determined from overload");
Douglas Gregor699ee522009-11-20 19:42:02 +00005597 if (SubExpr == ICE->getSubExpr())
5598 return ICE->Retain();
5599
5600 return new (Context) ImplicitCastExpr(ICE->getType(),
5601 ICE->getCastKind(),
5602 SubExpr,
5603 ICE->isLvalueCast());
5604 }
5605
5606 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00005607 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00005608 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00005609 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5610 if (Method->isStatic()) {
5611 // Do nothing: static member functions aren't any different
5612 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00005613 } else {
5614 // Fix the sub expression, which really has to be one of:
5615 // * a DeclRefExpr holding a member function template
5616 // * a TemplateIdRefExpr, also holding a member function template
5617 // * an UnresolvedLookupExpr holding an overloaded member function
5618 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5619 if (SubExpr == UnOp->getSubExpr())
5620 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00005621
John McCallba135432009-11-21 08:51:07 +00005622 assert(isa<DeclRefExpr>(SubExpr)
5623 && "fixed to something other than a decl ref");
5624 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
5625 && "fixed to a member ref with no nested name qualifier");
5626
5627 // We have taken the address of a pointer to member
5628 // function. Perform the computation here so that we get the
5629 // appropriate pointer to member type.
5630 QualType ClassType
5631 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5632 QualType MemPtrType
5633 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
5634
5635 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5636 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00005637 }
John McCallba135432009-11-21 08:51:07 +00005638
Douglas Gregor423a4e02009-10-22 18:02:20 +00005639 // FIXME: TemplateIdRefExpr referring to a member function template
5640 // specialization!
Douglas Gregorb86b0572009-02-11 01:18:59 +00005641 }
Douglas Gregor699ee522009-11-20 19:42:02 +00005642 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5643 if (SubExpr == UnOp->getSubExpr())
5644 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00005645
Douglas Gregor699ee522009-11-20 19:42:02 +00005646 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5647 Context.getPointerType(SubExpr->getType()),
5648 UnOp->getOperatorLoc());
5649 }
5650
5651 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
John McCallba135432009-11-21 08:51:07 +00005652 assert((isa<FunctionTemplateDecl>(DRE->getDecl()) ||
Douglas Gregor699ee522009-11-20 19:42:02 +00005653 isa<FunctionDecl>(DRE->getDecl())) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00005654 "Expected function or function template");
Douglas Gregor699ee522009-11-20 19:42:02 +00005655 return DeclRefExpr::Create(Context,
5656 DRE->getQualifier(),
5657 DRE->getQualifierRange(),
5658 Fn,
5659 DRE->getLocation(),
5660 DRE->hasExplicitTemplateArgumentList(),
5661 DRE->getLAngleLoc(),
5662 DRE->getTemplateArgs(),
5663 DRE->getNumTemplateArgs(),
5664 DRE->getRAngleLoc(),
5665 Fn->getType(),
5666 DRE->isTypeDependent(),
5667 DRE->isValueDependent());
5668 }
John McCallba135432009-11-21 08:51:07 +00005669
5670 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
5671 return DeclRefExpr::Create(Context,
5672 ULE->getQualifier(),
5673 ULE->getQualifierRange(),
5674 Fn,
5675 ULE->getNameLoc(),
5676 Fn->getType(),
5677 Fn->getType()->isDependentType(),
5678 false);
5679 }
5680
Douglas Gregor699ee522009-11-20 19:42:02 +00005681
5682 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
5683 assert((isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
5684 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl()) ||
5685 isa<FunctionDecl>(MemExpr->getMemberDecl())) &&
5686 "Expected member function or member function template");
5687 return MemberExpr::Create(Context, MemExpr->getBase()->Retain(),
5688 MemExpr->isArrow(),
5689 MemExpr->getQualifier(),
5690 MemExpr->getQualifierRange(),
5691 Fn,
5692 MemExpr->getMemberLoc(),
5693 MemExpr->hasExplicitTemplateArgumentList(),
5694 MemExpr->getLAngleLoc(),
5695 MemExpr->getTemplateArgs(),
5696 MemExpr->getNumTemplateArgs(),
5697 MemExpr->getRAngleLoc(),
5698 Fn->getType());
5699 }
5700
5701 if (TemplateIdRefExpr *TID = dyn_cast<TemplateIdRefExpr>(E)) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00005702 // FIXME: Don't destroy TID here, since we need its template arguments
5703 // to survive.
5704 // TID->Destroy(Context);
Douglas Gregor699ee522009-11-20 19:42:02 +00005705 return DeclRefExpr::Create(Context,
5706 TID->getQualifier(), TID->getQualifierRange(),
5707 Fn, TID->getTemplateNameLoc(),
5708 true,
5709 TID->getLAngleLoc(),
5710 TID->getTemplateArgs(),
5711 TID->getNumTemplateArgs(),
5712 TID->getRAngleLoc(),
5713 Fn->getType(),
5714 /*FIXME?*/false, /*FIXME?*/false);
5715 }
5716
Douglas Gregor699ee522009-11-20 19:42:02 +00005717 assert(false && "Invalid reference to overloaded function");
5718 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00005719}
5720
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005721} // end namespace clang