blob: 05e06a33ef579b9523ba1a4828da0a53b7cf1d3b [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 Gregor4c2458a2009-12-22 21:44:34 +000016#include "SemaInit.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000027#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,
Douglas Gregor43c79c22009-12-09 00:47:37 +000042 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000043 ICC_Qualification_Adjustment,
44 ICC_Promotion,
45 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000046 ICC_Promotion,
47 ICC_Conversion,
48 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000049 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
53 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000054 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000055 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000056 ICC_Conversion
57 };
58 return Category[(int)Kind];
59}
60
61/// GetConversionRank - Retrieve the implicit conversion rank
62/// corresponding to the given implicit conversion kind.
63ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
64 static const ImplicitConversionRank
65 Rank[(int)ICK_Num_Conversion_Kinds] = {
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
70 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +000071 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000072 ICR_Promotion,
73 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000074 ICR_Promotion,
75 ICR_Conversion,
76 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000077 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
81 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000082 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000083 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000084 ICR_Conversion
85 };
86 return Rank[(int)Kind];
87}
88
89/// GetImplicitConversionName - Return the name of this kind of
90/// implicit conversion.
91const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +000092 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000093 "No conversion",
94 "Lvalue-to-rvalue",
95 "Array-to-pointer",
96 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +000097 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000098 "Qualification",
99 "Integral promotion",
100 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000101 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000102 "Integral conversion",
103 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000104 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000105 "Floating-integral conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000106 "Complex-real conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000107 "Pointer conversion",
108 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000109 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000110 "Compatible-types conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000111 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000112 };
113 return Name[Kind];
114}
115
Douglas Gregor60d62c22008-10-31 16:23:19 +0000116/// StandardConversionSequence - Set the standard conversion
117/// sequence to the identity conversion.
118void StandardConversionSequence::setAsIdentityConversion() {
119 First = ICK_Identity;
120 Second = ICK_Identity;
121 Third = ICK_Identity;
122 Deprecated = false;
123 ReferenceBinding = false;
124 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000125 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000126 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000127}
128
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000129/// getRank - Retrieve the rank of this standard conversion sequence
130/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
131/// implicit conversions.
132ImplicitConversionRank StandardConversionSequence::getRank() const {
133 ImplicitConversionRank Rank = ICR_Exact_Match;
134 if (GetConversionRank(First) > Rank)
135 Rank = GetConversionRank(First);
136 if (GetConversionRank(Second) > Rank)
137 Rank = GetConversionRank(Second);
138 if (GetConversionRank(Third) > Rank)
139 Rank = GetConversionRank(Third);
140 return Rank;
141}
142
143/// isPointerConversionToBool - Determines whether this conversion is
144/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000145/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000146/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000147bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000148 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
149 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
150
151 // Note that FromType has not necessarily been transformed by the
152 // array-to-pointer or function-to-pointer implicit conversions, so
153 // check for their presence as well as checking whether FromType is
154 // a pointer.
155 if (ToType->isBooleanType() &&
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000156 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000157 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
158 return true;
159
160 return false;
161}
162
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000163/// isPointerConversionToVoidPointer - Determines whether this
164/// conversion is a conversion of a pointer to a void pointer. This is
165/// used as part of the ranking of standard conversion sequences (C++
166/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000167bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000168StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000169isPointerConversionToVoidPointer(ASTContext& Context) const {
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000170 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
171 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
172
173 // Note that FromType has not necessarily been transformed by the
174 // array-to-pointer implicit conversion, so check for its presence
175 // and redo the conversion to get a pointer.
176 if (First == ICK_Array_To_Pointer)
177 FromType = Context.getArrayDecayedType(FromType);
178
Douglas Gregor01919692009-12-13 21:37:05 +0000179 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000180 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000181 return ToPtrType->getPointeeType()->isVoidType();
182
183 return false;
184}
185
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000186/// DebugPrint - Print this standard conversion sequence to standard
187/// error. Useful for debugging overloading issues.
188void StandardConversionSequence::DebugPrint() const {
189 bool PrintedSomething = false;
190 if (First != ICK_Identity) {
191 fprintf(stderr, "%s", GetImplicitConversionName(First));
192 PrintedSomething = true;
193 }
194
195 if (Second != ICK_Identity) {
196 if (PrintedSomething) {
197 fprintf(stderr, " -> ");
198 }
199 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor225c41e2008-11-03 19:09:14 +0000200
201 if (CopyConstructor) {
202 fprintf(stderr, " (by copy constructor)");
203 } else if (DirectBinding) {
204 fprintf(stderr, " (direct reference binding)");
205 } else if (ReferenceBinding) {
206 fprintf(stderr, " (reference binding)");
207 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000208 PrintedSomething = true;
209 }
210
211 if (Third != ICK_Identity) {
212 if (PrintedSomething) {
213 fprintf(stderr, " -> ");
214 }
215 fprintf(stderr, "%s", GetImplicitConversionName(Third));
216 PrintedSomething = true;
217 }
218
219 if (!PrintedSomething) {
220 fprintf(stderr, "No conversions required");
221 }
222}
223
224/// DebugPrint - Print this user-defined conversion sequence to standard
225/// error. Useful for debugging overloading issues.
226void UserDefinedConversionSequence::DebugPrint() const {
227 if (Before.First || Before.Second || Before.Third) {
228 Before.DebugPrint();
229 fprintf(stderr, " -> ");
230 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000231 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000232 if (After.First || After.Second || After.Third) {
233 fprintf(stderr, " -> ");
234 After.DebugPrint();
235 }
236}
237
238/// DebugPrint - Print this implicit conversion sequence to standard
239/// error. Useful for debugging overloading issues.
240void ImplicitConversionSequence::DebugPrint() const {
241 switch (ConversionKind) {
242 case StandardConversion:
243 fprintf(stderr, "Standard conversion: ");
244 Standard.DebugPrint();
245 break;
246 case UserDefinedConversion:
247 fprintf(stderr, "User-defined conversion: ");
248 UserDefined.DebugPrint();
249 break;
250 case EllipsisConversion:
251 fprintf(stderr, "Ellipsis conversion");
252 break;
253 case BadConversion:
254 fprintf(stderr, "Bad conversion");
255 break;
256 }
257
258 fprintf(stderr, "\n");
259}
260
261// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000262// overload of the declarations in Old. This routine returns false if
263// New and Old cannot be overloaded, e.g., if New has the same
264// signature as some function in Old (C++ 1.3.10) or if the Old
265// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000266// it does return false, MatchedDecl will point to the decl that New
267// cannot be overloaded with. This decl may be a UsingShadowDecl on
268// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000269//
270// Example: Given the following input:
271//
272// void f(int, float); // #1
273// void f(int, int); // #2
274// int f(int, int); // #3
275//
276// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000277// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000278//
John McCall51fa86f2009-12-02 08:47:38 +0000279// When we process #2, Old contains only the FunctionDecl for #1. By
280// comparing the parameter types, we see that #1 and #2 are overloaded
281// (since they have different signatures), so this routine returns
282// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000283//
John McCall51fa86f2009-12-02 08:47:38 +0000284// When we process #3, Old is an overload set containing #1 and #2. We
285// compare the signatures of #3 to #1 (they're overloaded, so we do
286// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
287// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000288// signature), IsOverload returns false and MatchedDecl will be set to
289// point to the FunctionDecl for #2.
John McCall871b2e72009-12-09 03:35:25 +0000290Sema::OverloadKind
John McCall9f54ad42009-12-10 09:41:52 +0000291Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
292 NamedDecl *&Match) {
John McCall51fa86f2009-12-02 08:47:38 +0000293 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000294 I != E; ++I) {
John McCall51fa86f2009-12-02 08:47:38 +0000295 NamedDecl *OldD = (*I)->getUnderlyingDecl();
296 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall68263142009-11-18 22:49:29 +0000297 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCall871b2e72009-12-09 03:35:25 +0000298 Match = *I;
299 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000300 }
John McCall51fa86f2009-12-02 08:47:38 +0000301 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall68263142009-11-18 22:49:29 +0000302 if (!IsOverload(New, OldF)) {
John McCall871b2e72009-12-09 03:35:25 +0000303 Match = *I;
304 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000305 }
John McCall9f54ad42009-12-10 09:41:52 +0000306 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
307 // We can overload with these, which can show up when doing
308 // redeclaration checks for UsingDecls.
309 assert(Old.getLookupKind() == LookupUsingDeclName);
310 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
311 // Optimistically assume that an unresolved using decl will
312 // overload; if it doesn't, we'll have to diagnose during
313 // template instantiation.
314 } else {
John McCall68263142009-11-18 22:49:29 +0000315 // (C++ 13p1):
316 // Only function declarations can be overloaded; object and type
317 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000318 Match = *I;
319 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000320 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000321 }
John McCall68263142009-11-18 22:49:29 +0000322
John McCall871b2e72009-12-09 03:35:25 +0000323 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000324}
325
326bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
327 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
328 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
329
330 // C++ [temp.fct]p2:
331 // A function template can be overloaded with other function templates
332 // and with normal (non-template) functions.
333 if ((OldTemplate == 0) != (NewTemplate == 0))
334 return true;
335
336 // Is the function New an overload of the function Old?
337 QualType OldQType = Context.getCanonicalType(Old->getType());
338 QualType NewQType = Context.getCanonicalType(New->getType());
339
340 // Compare the signatures (C++ 1.3.10) of the two functions to
341 // determine whether they are overloads. If we find any mismatch
342 // in the signature, they are overloads.
343
344 // If either of these functions is a K&R-style function (no
345 // prototype), then we consider them to have matching signatures.
346 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
347 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
348 return false;
349
350 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
351 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
352
353 // The signature of a function includes the types of its
354 // parameters (C++ 1.3.10), which includes the presence or absence
355 // of the ellipsis; see C++ DR 357).
356 if (OldQType != NewQType &&
357 (OldType->getNumArgs() != NewType->getNumArgs() ||
358 OldType->isVariadic() != NewType->isVariadic() ||
359 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
360 NewType->arg_type_begin())))
361 return true;
362
363 // C++ [temp.over.link]p4:
364 // The signature of a function template consists of its function
365 // signature, its return type and its template parameter list. The names
366 // of the template parameters are significant only for establishing the
367 // relationship between the template parameters and the rest of the
368 // signature.
369 //
370 // We check the return type and template parameter lists for function
371 // templates first; the remaining checks follow.
372 if (NewTemplate &&
373 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
374 OldTemplate->getTemplateParameters(),
375 false, TPL_TemplateMatch) ||
376 OldType->getResultType() != NewType->getResultType()))
377 return true;
378
379 // If the function is a class member, its signature includes the
380 // cv-qualifiers (if any) on the function itself.
381 //
382 // As part of this, also check whether one of the member functions
383 // is static, in which case they are not overloads (C++
384 // 13.1p2). While not part of the definition of the signature,
385 // this check is important to determine whether these functions
386 // can be overloaded.
387 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
388 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
389 if (OldMethod && NewMethod &&
390 !OldMethod->isStatic() && !NewMethod->isStatic() &&
391 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
392 return true;
393
394 // The signatures match; this is not an overload.
395 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000396}
397
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000398/// TryImplicitConversion - Attempt to perform an implicit conversion
399/// from the given expression (Expr) to the given type (ToType). This
400/// function returns an implicit conversion sequence that can be used
401/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000402///
403/// void f(float f);
404/// void g(int i) { f(i); }
405///
406/// this routine would produce an implicit conversion sequence to
407/// describe the initialization of f from i, which will be a standard
408/// conversion sequence containing an lvalue-to-rvalue conversion (C++
409/// 4.1) followed by a floating-integral conversion (C++ 4.9).
410//
411/// Note that this routine only determines how the conversion can be
412/// performed; it does not actually perform the conversion. As such,
413/// it will not produce any diagnostics if no conversion is available,
414/// but will instead return an implicit conversion sequence of kind
415/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000416///
417/// If @p SuppressUserConversions, then user-defined conversions are
418/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000419/// If @p AllowExplicit, then explicit user-defined conversions are
420/// permitted.
Sebastian Redle2b68332009-04-12 17:16:29 +0000421/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
422/// no matter its actual lvalueness.
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000423/// If @p UserCast, the implicit conversion is being done for a user-specified
424/// cast.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000425ImplicitConversionSequence
Anders Carlsson2974b5c2009-08-27 17:14:02 +0000426Sema::TryImplicitConversion(Expr* From, QualType ToType,
427 bool SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +0000428 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000429 bool InOverloadResolution,
430 bool UserCast) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000431 ImplicitConversionSequence ICS;
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +0000432 OverloadCandidateSet Conversions;
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000433 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson08972922009-08-28 15:33:32 +0000434 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor60d62c22008-10-31 16:23:19 +0000435 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000436 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000437 (UserDefResult = IsUserDefinedConversion(From, ToType,
438 ICS.UserDefined,
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +0000439 Conversions,
Sebastian Redle2b68332009-04-12 17:16:29 +0000440 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000441 ForceRValue, UserCast)) == OR_Success) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000442 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000443 // C++ [over.ics.user]p4:
444 // A conversion of an expression of class type to the same class
445 // type is given Exact Match rank, and a conversion of an
446 // expression of class type to a base class of that type is
447 // given Conversion rank, in spite of the fact that a copy
448 // constructor (i.e., a user-defined conversion function) is
449 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000450 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000451 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000452 QualType FromCanon
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000453 = Context.getCanonicalType(From->getType().getUnqualifiedType());
454 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000455 if (Constructor->isCopyConstructor() &&
Douglas Gregor0d6d12b2009-12-22 00:21:20 +0000456 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000457 // Turn this into a "standard" conversion sequence, so that it
458 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000459 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
460 ICS.Standard.setAsIdentityConversion();
461 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
462 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000463 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000464 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000465 ICS.Standard.Second = ICK_Derived_To_Base;
466 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000467 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000468
469 // C++ [over.best.ics]p4:
470 // However, when considering the argument of a user-defined
471 // conversion function that is a candidate by 13.3.1.3 when
472 // invoked for the copying of the temporary in the second step
473 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
474 // 13.3.1.6 in all cases, only standard conversion sequences and
475 // ellipsis conversion sequences are allowed.
476 if (SuppressUserConversions &&
477 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
478 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000479 } else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000480 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000481 if (UserDefResult == OR_Ambiguous) {
482 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
483 Cand != Conversions.end(); ++Cand)
Fariborz Jahanian27687cf2009-10-12 17:51:19 +0000484 if (Cand->Viable)
485 ICS.ConversionFunctionSet.push_back(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000486 }
487 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000488
489 return ICS;
490}
491
Douglas Gregor43c79c22009-12-09 00:47:37 +0000492/// \brief Determine whether the conversion from FromType to ToType is a valid
493/// conversion that strips "noreturn" off the nested function type.
494static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
495 QualType ToType, QualType &ResultTy) {
496 if (Context.hasSameUnqualifiedType(FromType, ToType))
497 return false;
498
499 // Strip the noreturn off the type we're converting from; noreturn can
500 // safely be removed.
501 FromType = Context.getNoReturnType(FromType, false);
502 if (!Context.hasSameUnqualifiedType(FromType, ToType))
503 return false;
504
505 ResultTy = FromType;
506 return true;
507}
508
Douglas Gregor60d62c22008-10-31 16:23:19 +0000509/// IsStandardConversion - Determines whether there is a standard
510/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
511/// expression From to the type ToType. Standard conversion sequences
512/// only consider non-class types; for conversions that involve class
513/// types, use TryImplicitConversion. If a conversion exists, SCS will
514/// contain the standard conversion sequence required to perform this
515/// conversion and this routine will return true. Otherwise, this
516/// routine will return false and the value of SCS is unspecified.
Mike Stump1eb44332009-09-09 15:08:12 +0000517bool
518Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000519 bool InOverloadResolution,
Mike Stump1eb44332009-09-09 15:08:12 +0000520 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000521 QualType FromType = From->getType();
522
Douglas Gregor60d62c22008-10-31 16:23:19 +0000523 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000524 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000525 SCS.Deprecated = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000526 SCS.IncompatibleObjC = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000527 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000528 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000529
Douglas Gregorf9201e02009-02-11 23:02:49 +0000530 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000531 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000532 if (FromType->isRecordType() || ToType->isRecordType()) {
533 if (getLangOptions().CPlusPlus)
534 return false;
535
Mike Stump1eb44332009-09-09 15:08:12 +0000536 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000537 }
538
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000539 // The first conversion can be an lvalue-to-rvalue conversion,
540 // array-to-pointer conversion, or function-to-pointer conversion
541 // (C++ 4p1).
542
Mike Stump1eb44332009-09-09 15:08:12 +0000543 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000544 // An lvalue (3.10) of a non-function, non-array type T can be
545 // converted to an rvalue.
546 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000547 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000548 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000549 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000550 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000551
552 // If T is a non-class type, the type of the rvalue is the
553 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000554 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
555 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000556 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000557 } else if (FromType->isArrayType()) {
558 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000559 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000560
561 // An lvalue or rvalue of type "array of N T" or "array of unknown
562 // bound of T" can be converted to an rvalue of type "pointer to
563 // T" (C++ 4.2p1).
564 FromType = Context.getArrayDecayedType(FromType);
565
566 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
567 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000568 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000569
570 // For the purpose of ranking in overload resolution
571 // (13.3.3.1.1), this conversion is considered an
572 // array-to-pointer conversion followed by a qualification
573 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000574 SCS.Second = ICK_Identity;
575 SCS.Third = ICK_Qualification;
576 SCS.ToTypePtr = ToType.getAsOpaquePtr();
577 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000578 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000579 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
580 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000581 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000582
583 // An lvalue of function type T can be converted to an rvalue of
584 // type "pointer to T." The result is a pointer to the
585 // function. (C++ 4.3p1).
586 FromType = Context.getPointerType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000587 } else if (FunctionDecl *Fn
Douglas Gregor43c79c22009-12-09 00:47:37 +0000588 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000589 // Address of overloaded function (C++ [over.over]).
Douglas Gregor904eed32008-11-10 20:40:00 +0000590 SCS.First = ICK_Function_To_Pointer;
591
592 // We were able to resolve the address of the overloaded function,
593 // so we can convert to the type of that function.
594 FromType = Fn->getType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000595 if (ToType->isLValueReferenceType())
596 FromType = Context.getLValueReferenceType(FromType);
597 else if (ToType->isRValueReferenceType())
598 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000599 else if (ToType->isMemberPointerType()) {
600 // Resolve address only succeeds if both sides are member pointers,
601 // but it doesn't have to be the same class. See DR 247.
602 // Note that this means that the type of &Derived::fn can be
603 // Ret (Base::*)(Args) if the fn overload actually found is from the
604 // base class, even if it was brought into the derived class via a
605 // using declaration. The standard isn't clear on this issue at all.
606 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
607 FromType = Context.getMemberPointerType(FromType,
608 Context.getTypeDeclType(M->getParent()).getTypePtr());
609 } else
Douglas Gregor904eed32008-11-10 20:40:00 +0000610 FromType = Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000611 } else {
612 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000613 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000614 }
615
616 // The second conversion can be an integral promotion, floating
617 // point promotion, integral conversion, floating point conversion,
618 // floating-integral conversion, pointer conversion,
619 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000620 // For overloading in C, this can also be a "compatible-type"
621 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000622 bool IncompatibleObjC = false;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000623 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000624 // The unqualified versions of the types are the same: there's no
625 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000626 SCS.Second = ICK_Identity;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000627 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000628 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000629 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000630 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000631 } else if (IsFloatingPointPromotion(FromType, ToType)) {
632 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000633 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000634 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000635 } else if (IsComplexPromotion(FromType, ToType)) {
636 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000637 SCS.Second = ICK_Complex_Promotion;
638 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000639 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000640 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000641 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000642 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000643 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000644 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
645 // Floating point conversions (C++ 4.8).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000646 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000647 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000648 } else if (FromType->isComplexType() && ToType->isComplexType()) {
649 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000650 SCS.Second = ICK_Complex_Conversion;
651 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000652 } else if ((FromType->isFloatingType() &&
653 ToType->isIntegralType() && (!ToType->isBooleanType() &&
654 !ToType->isEnumeralType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000655 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000656 ToType->isFloatingType())) {
657 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000658 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000659 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000660 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
661 (ToType->isComplexType() && FromType->isArithmeticType())) {
662 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000663 SCS.Second = ICK_Complex_Real;
664 FromType = ToType.getUnqualifiedType();
Anders Carlsson08972922009-08-28 15:33:32 +0000665 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
666 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000667 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000668 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000669 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregorce940492009-09-25 04:25:58 +0000670 } else if (IsMemberPointerConversion(From, FromType, ToType,
671 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000672 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000673 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000674 } else if (ToType->isBooleanType() &&
675 (FromType->isArithmeticType() ||
676 FromType->isEnumeralType() ||
Fariborz Jahanian1f7711d2009-12-11 21:23:13 +0000677 FromType->isAnyPointerType() ||
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000678 FromType->isBlockPointerType() ||
679 FromType->isMemberPointerType() ||
680 FromType->isNullPtrType())) {
681 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000682 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000683 FromType = Context.BoolTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000684 } else if (!getLangOptions().CPlusPlus &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000685 Context.typesAreCompatible(ToType, FromType)) {
686 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000687 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor43c79c22009-12-09 00:47:37 +0000688 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
689 // Treat a conversion that strips "noreturn" as an identity conversion.
690 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000691 } else {
692 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000693 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000694 }
695
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000696 QualType CanonFrom;
697 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000698 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000699 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000700 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000701 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000702 CanonFrom = Context.getCanonicalType(FromType);
703 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000704 } else {
705 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000706 SCS.Third = ICK_Identity;
707
Mike Stump1eb44332009-09-09 15:08:12 +0000708 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +0000709 // [...] Any difference in top-level cv-qualification is
710 // subsumed by the initialization itself and does not constitute
711 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000712 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000713 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +0000714 if (CanonFrom.getLocalUnqualifiedType()
715 == CanonTo.getLocalUnqualifiedType() &&
716 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000717 FromType = ToType;
718 CanonFrom = CanonTo;
719 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000720 }
721
722 // If we have not converted the argument type to the parameter type,
723 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000724 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000725 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000726
Douglas Gregor60d62c22008-10-31 16:23:19 +0000727 SCS.ToTypePtr = FromType.getAsOpaquePtr();
728 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000729}
730
731/// IsIntegralPromotion - Determines whether the conversion from the
732/// expression From (whose potentially-adjusted type is FromType) to
733/// ToType is an integral promotion (C++ 4.5). If so, returns true and
734/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000735bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000736 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000737 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000738 if (!To) {
739 return false;
740 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000741
742 // An rvalue of type char, signed char, unsigned char, short int, or
743 // unsigned short int can be converted to an rvalue of type int if
744 // int can represent all the values of the source type; otherwise,
745 // the source rvalue can be converted to an rvalue of type unsigned
746 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000747 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000748 if (// We can promote any signed, promotable integer type to an int
749 (FromType->isSignedIntegerType() ||
750 // We can promote any unsigned integer type whose size is
751 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +0000752 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000753 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000754 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000755 }
756
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000757 return To->getKind() == BuiltinType::UInt;
758 }
759
760 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
761 // can be converted to an rvalue of the first of the following types
762 // that can represent all the values of its underlying type: int,
763 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall842aef82009-12-09 09:09:27 +0000764
765 // We pre-calculate the promotion type for enum types.
766 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
767 if (ToType->isIntegerType())
768 return Context.hasSameUnqualifiedType(ToType,
769 FromEnumType->getDecl()->getPromotionType());
770
771 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000772 // Determine whether the type we're converting from is signed or
773 // unsigned.
774 bool FromIsSigned;
775 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +0000776
777 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
778 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000779
780 // The types we'll try to promote to, in the appropriate
781 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +0000782 QualType PromoteTypes[6] = {
783 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000784 Context.LongTy, Context.UnsignedLongTy ,
785 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000786 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000787 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000788 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
789 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +0000790 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000791 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
792 // We found the type that we can promote to. If this is the
793 // type we wanted, we have a promotion. Otherwise, no
794 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000795 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000796 }
797 }
798 }
799
800 // An rvalue for an integral bit-field (9.6) can be converted to an
801 // rvalue of type int if int can represent all the values of the
802 // bit-field; otherwise, it can be converted to unsigned int if
803 // unsigned int can represent all the values of the bit-field. If
804 // the bit-field is larger yet, no integral promotion applies to
805 // it. If the bit-field has an enumerated type, it is treated as any
806 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +0000807 // FIXME: We should delay checking of bit-fields until we actually perform the
808 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000809 using llvm::APSInt;
810 if (From)
811 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +0000812 APSInt BitWidth;
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000813 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
814 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
815 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
816 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Douglas Gregor86f19402008-12-20 23:49:58 +0000818 // Are we promoting to an int from a bitfield that fits in an int?
819 if (BitWidth < ToSize ||
820 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
821 return To->getKind() == BuiltinType::Int;
822 }
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Douglas Gregor86f19402008-12-20 23:49:58 +0000824 // Are we promoting to an unsigned int from an unsigned bitfield
825 // that fits into an unsigned int?
826 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
827 return To->getKind() == BuiltinType::UInt;
828 }
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Douglas Gregor86f19402008-12-20 23:49:58 +0000830 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000831 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000832 }
Mike Stump1eb44332009-09-09 15:08:12 +0000833
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000834 // An rvalue of type bool can be converted to an rvalue of type int,
835 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000836 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000837 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000838 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000839
840 return false;
841}
842
843/// IsFloatingPointPromotion - Determines whether the conversion from
844/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
845/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000846bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000847 /// An rvalue of type float can be converted to an rvalue of type
848 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +0000849 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
850 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000851 if (FromBuiltin->getKind() == BuiltinType::Float &&
852 ToBuiltin->getKind() == BuiltinType::Double)
853 return true;
854
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000855 // C99 6.3.1.5p1:
856 // When a float is promoted to double or long double, or a
857 // double is promoted to long double [...].
858 if (!getLangOptions().CPlusPlus &&
859 (FromBuiltin->getKind() == BuiltinType::Float ||
860 FromBuiltin->getKind() == BuiltinType::Double) &&
861 (ToBuiltin->getKind() == BuiltinType::LongDouble))
862 return true;
863 }
864
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000865 return false;
866}
867
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000868/// \brief Determine if a conversion is a complex promotion.
869///
870/// A complex promotion is defined as a complex -> complex conversion
871/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000872/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000873bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000874 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000875 if (!FromComplex)
876 return false;
877
John McCall183700f2009-09-21 23:43:11 +0000878 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000879 if (!ToComplex)
880 return false;
881
882 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000883 ToComplex->getElementType()) ||
884 IsIntegralPromotion(0, FromComplex->getElementType(),
885 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000886}
887
Douglas Gregorcb7de522008-11-26 23:31:11 +0000888/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
889/// the pointer type FromPtr to a pointer to type ToPointee, with the
890/// same type qualifiers as FromPtr has on its pointee type. ToType,
891/// if non-empty, will be a pointer to ToType that may or may not have
892/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +0000893static QualType
894BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000895 QualType ToPointee, QualType ToType,
896 ASTContext &Context) {
897 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
898 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +0000899 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +0000900
901 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000902 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +0000903 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +0000904 if (!ToType.isNull())
Douglas Gregorcb7de522008-11-26 23:31:11 +0000905 return ToType;
906
907 // Build a pointer to ToPointee. It has the right qualifiers
908 // already.
909 return Context.getPointerType(ToPointee);
910 }
911
912 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +0000913 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +0000914 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
915 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +0000916}
917
Fariborz Jahanianadcfab12009-12-16 23:13:33 +0000918/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
919/// the FromType, which is an objective-c pointer, to ToType, which may or may
920/// not have the right set of qualifiers.
921static QualType
922BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
923 QualType ToType,
924 ASTContext &Context) {
925 QualType CanonFromType = Context.getCanonicalType(FromType);
926 QualType CanonToType = Context.getCanonicalType(ToType);
927 Qualifiers Quals = CanonFromType.getQualifiers();
928
929 // Exact qualifier match -> return the pointer type we're converting to.
930 if (CanonToType.getLocalQualifiers() == Quals)
931 return ToType;
932
933 // Just build a canonical type that has the right qualifiers.
934 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
935}
936
Mike Stump1eb44332009-09-09 15:08:12 +0000937static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000938 bool InOverloadResolution,
939 ASTContext &Context) {
940 // Handle value-dependent integral null pointer constants correctly.
941 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
942 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
943 Expr->getType()->isIntegralType())
944 return !InOverloadResolution;
945
Douglas Gregorce940492009-09-25 04:25:58 +0000946 return Expr->isNullPointerConstant(Context,
947 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
948 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000949}
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000951/// IsPointerConversion - Determines whether the conversion of the
952/// expression From, which has the (possibly adjusted) type FromType,
953/// can be converted to the type ToType via a pointer conversion (C++
954/// 4.10). If so, returns true and places the converted type (that
955/// might differ from ToType in its cv-qualifiers at some level) into
956/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000957///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000958/// This routine also supports conversions to and from block pointers
959/// and conversions with Objective-C's 'id', 'id<protocols...>', and
960/// pointers to interfaces. FIXME: Once we've determined the
961/// appropriate overloading rules for Objective-C, we may want to
962/// split the Objective-C checks into a different routine; however,
963/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000964/// conversions, so for now they live here. IncompatibleObjC will be
965/// set if the conversion is an allowed Objective-C conversion that
966/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000967bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000968 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +0000969 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +0000970 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +0000971 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000972 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
973 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000974
Mike Stump1eb44332009-09-09 15:08:12 +0000975 // Conversion from a null pointer constant to any Objective-C pointer type.
976 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000977 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +0000978 ConvertedType = ToType;
979 return true;
980 }
981
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000982 // Blocks: Block pointers can be converted to void*.
983 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000984 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000985 ConvertedType = ToType;
986 return true;
987 }
988 // Blocks: A null pointer constant can be converted to a block
989 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +0000990 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000991 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000992 ConvertedType = ToType;
993 return true;
994 }
995
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000996 // If the left-hand-side is nullptr_t, the right side can be a null
997 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +0000998 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000999 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001000 ConvertedType = ToType;
1001 return true;
1002 }
1003
Ted Kremenek6217b802009-07-29 21:53:49 +00001004 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001005 if (!ToTypePtr)
1006 return false;
1007
1008 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001009 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001010 ConvertedType = ToType;
1011 return true;
1012 }
Sebastian Redl07779722008-10-31 14:43:28 +00001013
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001014 // Beyond this point, both types need to be pointers
1015 // , including objective-c pointers.
1016 QualType ToPointeeType = ToTypePtr->getPointeeType();
1017 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1018 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1019 ToType, Context);
1020 return true;
1021
1022 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001023 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001024 if (!FromTypePtr)
1025 return false;
1026
1027 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001028
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001029 // An rvalue of type "pointer to cv T," where T is an object type,
1030 // can be converted to an rvalue of type "pointer to cv void" (C++
1031 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +00001032 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001033 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001034 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001035 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001036 return true;
1037 }
1038
Douglas Gregorf9201e02009-02-11 23:02:49 +00001039 // When we're overloading in C, we allow a special kind of pointer
1040 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001041 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001042 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001043 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001044 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001045 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001046 return true;
1047 }
1048
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001049 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001050 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001051 // An rvalue of type "pointer to cv D," where D is a class type,
1052 // can be converted to an rvalue of type "pointer to cv B," where
1053 // B is a base class (clause 10) of D. If B is an inaccessible
1054 // (clause 11) or ambiguous (10.2) base class of D, a program that
1055 // necessitates this conversion is ill-formed. The result of the
1056 // conversion is a pointer to the base class sub-object of the
1057 // derived class object. The null pointer value is converted to
1058 // the null pointer value of the destination type.
1059 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001060 // Note that we do not check for ambiguity or inaccessibility
1061 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001062 if (getLangOptions().CPlusPlus &&
1063 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001064 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001065 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001066 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001067 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001068 ToType, Context);
1069 return true;
1070 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001071
Douglas Gregorc7887512008-12-19 19:13:09 +00001072 return false;
1073}
1074
1075/// isObjCPointerConversion - Determines whether this is an
1076/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1077/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001078bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001079 QualType& ConvertedType,
1080 bool &IncompatibleObjC) {
1081 if (!getLangOptions().ObjC1)
1082 return false;
1083
Steve Naroff14108da2009-07-10 23:34:53 +00001084 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001085 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001086 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001087 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001088
Steve Naroff14108da2009-07-10 23:34:53 +00001089 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001090 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001091 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001092 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001093 ConvertedType = ToType;
1094 return true;
1095 }
1096 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001097 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001098 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001099 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001100 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001101 ConvertedType = ToType;
1102 return true;
1103 }
1104 // Objective C++: We're able to convert from a pointer to an
1105 // interface to a pointer to a different interface.
1106 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1107 ConvertedType = ToType;
1108 return true;
1109 }
1110
1111 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1112 // Okay: this is some kind of implicit downcast of Objective-C
1113 // interfaces, which is permitted. However, we're going to
1114 // complain about it.
1115 IncompatibleObjC = true;
1116 ConvertedType = FromType;
1117 return true;
1118 }
Mike Stump1eb44332009-09-09 15:08:12 +00001119 }
Steve Naroff14108da2009-07-10 23:34:53 +00001120 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001121 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001122 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001123 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001124 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001125 ToPointeeType = ToBlockPtr->getPointeeType();
1126 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001127 return false;
1128
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001129 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001130 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001131 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001132 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001133 FromPointeeType = FromBlockPtr->getPointeeType();
1134 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001135 return false;
1136
Douglas Gregorc7887512008-12-19 19:13:09 +00001137 // If we have pointers to pointers, recursively check whether this
1138 // is an Objective-C conversion.
1139 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1140 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1141 IncompatibleObjC)) {
1142 // We always complain about this conversion.
1143 IncompatibleObjC = true;
1144 ConvertedType = ToType;
1145 return true;
1146 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001147 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001148 // differences in the argument and result types are in Objective-C
1149 // pointer conversions. If so, we permit the conversion (but
1150 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001151 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001152 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001153 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001154 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001155 if (FromFunctionType && ToFunctionType) {
1156 // If the function types are exactly the same, this isn't an
1157 // Objective-C pointer conversion.
1158 if (Context.getCanonicalType(FromPointeeType)
1159 == Context.getCanonicalType(ToPointeeType))
1160 return false;
1161
1162 // Perform the quick checks that will tell us whether these
1163 // function types are obviously different.
1164 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1165 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1166 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1167 return false;
1168
1169 bool HasObjCConversion = false;
1170 if (Context.getCanonicalType(FromFunctionType->getResultType())
1171 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1172 // Okay, the types match exactly. Nothing to do.
1173 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1174 ToFunctionType->getResultType(),
1175 ConvertedType, IncompatibleObjC)) {
1176 // Okay, we have an Objective-C pointer conversion.
1177 HasObjCConversion = true;
1178 } else {
1179 // Function types are too different. Abort.
1180 return false;
1181 }
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Douglas Gregorc7887512008-12-19 19:13:09 +00001183 // Check argument types.
1184 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1185 ArgIdx != NumArgs; ++ArgIdx) {
1186 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1187 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1188 if (Context.getCanonicalType(FromArgType)
1189 == Context.getCanonicalType(ToArgType)) {
1190 // Okay, the types match exactly. Nothing to do.
1191 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1192 ConvertedType, IncompatibleObjC)) {
1193 // Okay, we have an Objective-C pointer conversion.
1194 HasObjCConversion = true;
1195 } else {
1196 // Argument types are too different. Abort.
1197 return false;
1198 }
1199 }
1200
1201 if (HasObjCConversion) {
1202 // We had an Objective-C conversion. Allow this pointer
1203 // conversion, but complain about it.
1204 ConvertedType = ToType;
1205 IncompatibleObjC = true;
1206 return true;
1207 }
1208 }
1209
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001210 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001211}
1212
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001213/// CheckPointerConversion - Check the pointer conversion from the
1214/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001215/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001216/// conversions for which IsPointerConversion has already returned
1217/// true. It returns true and produces a diagnostic if there was an
1218/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001219bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001220 CastExpr::CastKind &Kind,
1221 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001222 QualType FromType = From->getType();
1223
Ted Kremenek6217b802009-07-29 21:53:49 +00001224 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1225 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001226 QualType FromPointeeType = FromPtrType->getPointeeType(),
1227 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001228
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001229 if (FromPointeeType->isRecordType() &&
1230 ToPointeeType->isRecordType()) {
1231 // We must have a derived-to-base conversion. Check an
1232 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001233 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1234 From->getExprLoc(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001235 From->getSourceRange(),
1236 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001237 return true;
1238
1239 // The conversion was successful.
1240 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001241 }
1242 }
Mike Stump1eb44332009-09-09 15:08:12 +00001243 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001244 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001245 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001246 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001247 // Objective-C++ conversions are always okay.
1248 // FIXME: We should have a different class of conversions for the
1249 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001250 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001251 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001252
Steve Naroff14108da2009-07-10 23:34:53 +00001253 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001254 return false;
1255}
1256
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001257/// IsMemberPointerConversion - Determines whether the conversion of the
1258/// expression From, which has the (possibly adjusted) type FromType, can be
1259/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1260/// If so, returns true and places the converted type (that might differ from
1261/// ToType in its cv-qualifiers at some level) into ConvertedType.
1262bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001263 QualType ToType,
1264 bool InOverloadResolution,
1265 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001266 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001267 if (!ToTypePtr)
1268 return false;
1269
1270 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001271 if (From->isNullPointerConstant(Context,
1272 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1273 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001274 ConvertedType = ToType;
1275 return true;
1276 }
1277
1278 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001279 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001280 if (!FromTypePtr)
1281 return false;
1282
1283 // A pointer to member of B can be converted to a pointer to member of D,
1284 // where D is derived from B (C++ 4.11p2).
1285 QualType FromClass(FromTypePtr->getClass(), 0);
1286 QualType ToClass(ToTypePtr->getClass(), 0);
1287 // FIXME: What happens when these are dependent? Is this function even called?
1288
1289 if (IsDerivedFrom(ToClass, FromClass)) {
1290 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1291 ToClass.getTypePtr());
1292 return true;
1293 }
1294
1295 return false;
1296}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001297
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001298/// CheckMemberPointerConversion - Check the member pointer conversion from the
1299/// expression From to the type ToType. This routine checks for ambiguous or
1300/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1301/// for which IsMemberPointerConversion has already returned true. It returns
1302/// true and produces a diagnostic if there was an error, or returns false
1303/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001304bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001305 CastExpr::CastKind &Kind,
1306 bool IgnoreBaseAccess) {
1307 (void)IgnoreBaseAccess;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001308 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001309 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001310 if (!FromPtrType) {
1311 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001312 assert(From->isNullPointerConstant(Context,
1313 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001314 "Expr must be null pointer constant!");
1315 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001316 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001317 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001318
Ted Kremenek6217b802009-07-29 21:53:49 +00001319 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001320 assert(ToPtrType && "No member pointer cast has a target type "
1321 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001322
Sebastian Redl21593ac2009-01-28 18:33:18 +00001323 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1324 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001325
Sebastian Redl21593ac2009-01-28 18:33:18 +00001326 // FIXME: What about dependent types?
1327 assert(FromClass->isRecordType() && "Pointer into non-class.");
1328 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001329
Douglas Gregora8f32e02009-10-06 17:59:45 +00001330 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1331 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001332 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1333 assert(DerivationOkay &&
1334 "Should not have been called if derivation isn't OK.");
1335 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001336
Sebastian Redl21593ac2009-01-28 18:33:18 +00001337 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1338 getUnqualifiedType())) {
1339 // Derivation is ambiguous. Redo the check to find the exact paths.
1340 Paths.clear();
1341 Paths.setRecordingPaths(true);
1342 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1343 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1344 (void)StillOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001345
Sebastian Redl21593ac2009-01-28 18:33:18 +00001346 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1347 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1348 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1349 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001350 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001351
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001352 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001353 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1354 << FromClass << ToClass << QualType(VBase, 0)
1355 << From->getSourceRange();
1356 return true;
1357 }
1358
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001359 // Must be a base to derived member conversion.
1360 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001361 return false;
1362}
1363
Douglas Gregor98cd5992008-10-21 23:43:52 +00001364/// IsQualificationConversion - Determines whether the conversion from
1365/// an rvalue of type FromType to ToType is a qualification conversion
1366/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001367bool
1368Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001369 FromType = Context.getCanonicalType(FromType);
1370 ToType = Context.getCanonicalType(ToType);
1371
1372 // If FromType and ToType are the same type, this is not a
1373 // qualification conversion.
1374 if (FromType == ToType)
1375 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001376
Douglas Gregor98cd5992008-10-21 23:43:52 +00001377 // (C++ 4.4p4):
1378 // A conversion can add cv-qualifiers at levels other than the first
1379 // in multi-level pointers, subject to the following rules: [...]
1380 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001381 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001382 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001383 // Within each iteration of the loop, we check the qualifiers to
1384 // determine if this still looks like a qualification
1385 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001386 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001387 // until there are no more pointers or pointers-to-members left to
1388 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001389 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001390
1391 // -- for every j > 0, if const is in cv 1,j then const is in cv
1392 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001393 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001394 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001395
Douglas Gregor98cd5992008-10-21 23:43:52 +00001396 // -- if the cv 1,j and cv 2,j are different, then const is in
1397 // every cv for 0 < k < j.
1398 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001399 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001400 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001401
Douglas Gregor98cd5992008-10-21 23:43:52 +00001402 // Keep track of whether all prior cv-qualifiers in the "to" type
1403 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001404 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001405 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001406 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001407
1408 // We are left with FromType and ToType being the pointee types
1409 // after unwrapping the original FromType and ToType the same number
1410 // of types. If we unwrapped any pointers, and if FromType and
1411 // ToType have the same unqualified type (since we checked
1412 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001413 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001414}
1415
Douglas Gregor734d9862009-01-30 23:27:23 +00001416/// Determines whether there is a user-defined conversion sequence
1417/// (C++ [over.ics.user]) that converts expression From to the type
1418/// ToType. If such a conversion exists, User will contain the
1419/// user-defined conversion sequence that performs such a conversion
1420/// and this routine will return true. Otherwise, this routine returns
1421/// false and User is unspecified.
1422///
1423/// \param AllowConversionFunctions true if the conversion should
1424/// consider conversion functions at all. If false, only constructors
1425/// will be considered.
1426///
1427/// \param AllowExplicit true if the conversion should consider C++0x
1428/// "explicit" conversion functions as well as non-explicit conversion
1429/// functions (C++0x [class.conv.fct]p2).
Sebastian Redle2b68332009-04-12 17:16:29 +00001430///
1431/// \param ForceRValue true if the expression should be treated as an rvalue
1432/// for overload resolution.
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001433/// \param UserCast true if looking for user defined conversion for a static
1434/// cast.
Douglas Gregor20093b42009-12-09 23:02:17 +00001435OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1436 UserDefinedConversionSequence& User,
1437 OverloadCandidateSet& CandidateSet,
1438 bool AllowConversionFunctions,
1439 bool AllowExplicit,
1440 bool ForceRValue,
1441 bool UserCast) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001442 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00001443 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1444 // We're not going to find any constructors.
1445 } else if (CXXRecordDecl *ToRecordDecl
1446 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001447 // C++ [over.match.ctor]p1:
1448 // When objects of class type are direct-initialized (8.5), or
1449 // copy-initialized from an expression of the same or a
1450 // derived class type (8.5), overload resolution selects the
1451 // constructor. [...] For copy-initialization, the candidate
1452 // functions are all the converting constructors (12.3.1) of
1453 // that class. The argument list is the expression-list within
1454 // the parentheses of the initializer.
Douglas Gregor79b680e2009-11-13 18:44:21 +00001455 bool SuppressUserConversions = !UserCast;
1456 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1457 IsDerivedFrom(From->getType(), ToType)) {
1458 SuppressUserConversions = false;
1459 AllowConversionFunctions = false;
1460 }
1461
Mike Stump1eb44332009-09-09 15:08:12 +00001462 DeclarationName ConstructorName
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001463 = Context.DeclarationNames.getCXXConstructorName(
1464 Context.getCanonicalType(ToType).getUnqualifiedType());
1465 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump1eb44332009-09-09 15:08:12 +00001466 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001467 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001468 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00001469 // Find the constructor (which may be a template).
1470 CXXConstructorDecl *Constructor = 0;
1471 FunctionTemplateDecl *ConstructorTmpl
1472 = dyn_cast<FunctionTemplateDecl>(*Con);
1473 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001474 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001475 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1476 else
1477 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001478
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001479 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001480 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001481 if (ConstructorTmpl)
John McCalld5532b62009-11-23 01:53:49 +00001482 AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
1483 &From, 1, CandidateSet,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001484 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001485 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001486 // Allow one user-defined conversion when user specifies a
1487 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregordec06662009-08-21 18:42:58 +00001488 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001489 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001490 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001491 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001492 }
1493 }
1494
Douglas Gregor734d9862009-01-30 23:27:23 +00001495 if (!AllowConversionFunctions) {
1496 // Don't allow any conversion functions to enter the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00001497 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1498 PDiag(0)
Anders Carlssonb7906612009-08-26 23:45:07 +00001499 << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001500 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001501 } else if (const RecordType *FromRecordType
Ted Kremenek6217b802009-07-29 21:53:49 +00001502 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001503 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001504 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1505 // Add all of the conversion functions as candidates.
John McCallba135432009-11-21 08:51:07 +00001506 const UnresolvedSet *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001507 = FromRecordDecl->getVisibleConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00001508 for (UnresolvedSet::iterator I = Conversions->begin(),
1509 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00001510 NamedDecl *D = *I;
1511 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1512 if (isa<UsingShadowDecl>(D))
1513 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1514
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001515 CXXConversionDecl *Conv;
1516 FunctionTemplateDecl *ConvTemplate;
John McCallba135432009-11-21 08:51:07 +00001517 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001518 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1519 else
John McCallba135432009-11-21 08:51:07 +00001520 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001521
1522 if (AllowExplicit || !Conv->isExplicit()) {
1523 if (ConvTemplate)
John McCall701c89e2009-12-03 04:06:58 +00001524 AddTemplateConversionCandidate(ConvTemplate, ActingContext,
1525 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001526 else
John McCall701c89e2009-12-03 04:06:58 +00001527 AddConversionCandidate(Conv, ActingContext, From, ToType,
1528 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001529 }
1530 }
1531 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001532 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001533
1534 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001535 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001536 case OR_Success:
1537 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001538 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001539 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1540 // C++ [over.ics.user]p1:
1541 // If the user-defined conversion is specified by a
1542 // constructor (12.3.1), the initial standard conversion
1543 // sequence converts the source type to the type required by
1544 // the argument of the constructor.
1545 //
Douglas Gregor60d62c22008-10-31 16:23:19 +00001546 QualType ThisType = Constructor->getThisType(Context);
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001547 if (Best->Conversions[0].ConversionKind ==
1548 ImplicitConversionSequence::EllipsisConversion)
1549 User.EllipsisConversion = true;
1550 else {
1551 User.Before = Best->Conversions[0].Standard;
1552 User.EllipsisConversion = false;
1553 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001554 User.ConversionFunction = Constructor;
1555 User.After.setAsIdentityConversion();
Mike Stump1eb44332009-09-09 15:08:12 +00001556 User.After.FromTypePtr
Ted Kremenek6217b802009-07-29 21:53:49 +00001557 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor60d62c22008-10-31 16:23:19 +00001558 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001559 return OR_Success;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001560 } else if (CXXConversionDecl *Conversion
1561 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1562 // C++ [over.ics.user]p1:
1563 //
1564 // [...] If the user-defined conversion is specified by a
1565 // conversion function (12.3.2), the initial standard
1566 // conversion sequence converts the source type to the
1567 // implicit object parameter of the conversion function.
1568 User.Before = Best->Conversions[0].Standard;
1569 User.ConversionFunction = Conversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001570 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001571
1572 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001573 // The second standard conversion sequence converts the
1574 // result of the user-defined conversion to the target type
1575 // for the sequence. Since an implicit conversion sequence
1576 // is an initialization, the special rules for
1577 // initialization by user-defined conversion apply when
1578 // selecting the best user-defined conversion for a
1579 // user-defined conversion sequence (see 13.3.3 and
1580 // 13.3.3.1).
1581 User.After = Best->FinalConversion;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001582 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001583 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001584 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001585 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001586 }
Mike Stump1eb44332009-09-09 15:08:12 +00001587
Douglas Gregor60d62c22008-10-31 16:23:19 +00001588 case OR_No_Viable_Function:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001589 return OR_No_Viable_Function;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001590 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001591 // No conversion here! We're done.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001592 return OR_Deleted;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001593
1594 case OR_Ambiguous:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001595 return OR_Ambiguous;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001596 }
1597
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001598 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001599}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001600
1601bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001602Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001603 ImplicitConversionSequence ICS;
1604 OverloadCandidateSet CandidateSet;
1605 OverloadingResult OvResult =
1606 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1607 CandidateSet, true, false, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001608 if (OvResult == OR_Ambiguous)
1609 Diag(From->getSourceRange().getBegin(),
1610 diag::err_typecheck_ambiguous_condition)
1611 << From->getType() << ToType << From->getSourceRange();
1612 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1613 Diag(From->getSourceRange().getBegin(),
1614 diag::err_typecheck_nonviable_condition)
1615 << From->getType() << ToType << From->getSourceRange();
1616 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001617 return false;
John McCall81201622010-01-08 04:41:39 +00001618 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001619 return true;
1620}
Douglas Gregor60d62c22008-10-31 16:23:19 +00001621
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001622/// CompareImplicitConversionSequences - Compare two implicit
1623/// conversion sequences to determine whether one is better than the
1624/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00001625ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001626Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1627 const ImplicitConversionSequence& ICS2)
1628{
1629 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1630 // conversion sequences (as defined in 13.3.3.1)
1631 // -- a standard conversion sequence (13.3.3.1.1) is a better
1632 // conversion sequence than a user-defined conversion sequence or
1633 // an ellipsis conversion sequence, and
1634 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1635 // conversion sequence than an ellipsis conversion sequence
1636 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00001637 //
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001638 if (ICS1.ConversionKind < ICS2.ConversionKind)
1639 return ImplicitConversionSequence::Better;
1640 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1641 return ImplicitConversionSequence::Worse;
1642
1643 // Two implicit conversion sequences of the same form are
1644 // indistinguishable conversion sequences unless one of the
1645 // following rules apply: (C++ 13.3.3.2p3):
1646 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1647 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump1eb44332009-09-09 15:08:12 +00001648 else if (ICS1.ConversionKind ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001649 ImplicitConversionSequence::UserDefinedConversion) {
1650 // User-defined conversion sequence U1 is a better conversion
1651 // sequence than another user-defined conversion sequence U2 if
1652 // they contain the same user-defined conversion function or
1653 // constructor and if the second standard conversion sequence of
1654 // U1 is better than the second standard conversion sequence of
1655 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001656 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001657 ICS2.UserDefined.ConversionFunction)
1658 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1659 ICS2.UserDefined.After);
1660 }
1661
1662 return ImplicitConversionSequence::Indistinguishable;
1663}
1664
1665/// CompareStandardConversionSequences - Compare two standard
1666/// conversion sequences to determine whether one is better than the
1667/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001668ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001669Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1670 const StandardConversionSequence& SCS2)
1671{
1672 // Standard conversion sequence S1 is a better conversion sequence
1673 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1674
1675 // -- S1 is a proper subsequence of S2 (comparing the conversion
1676 // sequences in the canonical form defined by 13.3.3.1.1,
1677 // excluding any Lvalue Transformation; the identity conversion
1678 // sequence is considered to be a subsequence of any
1679 // non-identity conversion sequence) or, if not that,
1680 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1681 // Neither is a proper subsequence of the other. Do nothing.
1682 ;
1683 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1684 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001685 (SCS1.Second == ICK_Identity &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001686 SCS1.Third == ICK_Identity))
1687 // SCS1 is a proper subsequence of SCS2.
1688 return ImplicitConversionSequence::Better;
1689 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1690 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001691 (SCS2.Second == ICK_Identity &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001692 SCS2.Third == ICK_Identity))
1693 // SCS2 is a proper subsequence of SCS1.
1694 return ImplicitConversionSequence::Worse;
1695
1696 // -- the rank of S1 is better than the rank of S2 (by the rules
1697 // defined below), or, if not that,
1698 ImplicitConversionRank Rank1 = SCS1.getRank();
1699 ImplicitConversionRank Rank2 = SCS2.getRank();
1700 if (Rank1 < Rank2)
1701 return ImplicitConversionSequence::Better;
1702 else if (Rank2 < Rank1)
1703 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001704
Douglas Gregor57373262008-10-22 14:17:15 +00001705 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1706 // are indistinguishable unless one of the following rules
1707 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Douglas Gregor57373262008-10-22 14:17:15 +00001709 // A conversion that is not a conversion of a pointer, or
1710 // pointer to member, to bool is better than another conversion
1711 // that is such a conversion.
1712 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1713 return SCS2.isPointerConversionToBool()
1714 ? ImplicitConversionSequence::Better
1715 : ImplicitConversionSequence::Worse;
1716
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001717 // C++ [over.ics.rank]p4b2:
1718 //
1719 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001720 // conversion of B* to A* is better than conversion of B* to
1721 // void*, and conversion of A* to void* is better than conversion
1722 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00001723 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001724 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001725 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001726 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001727 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1728 // Exactly one of the conversion sequences is a conversion to
1729 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001730 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1731 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001732 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1733 // Neither conversion sequence converts to a void pointer; compare
1734 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001735 if (ImplicitConversionSequence::CompareKind DerivedCK
1736 = CompareDerivedToBaseConversions(SCS1, SCS2))
1737 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001738 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1739 // Both conversion sequences are conversions to void
1740 // pointers. Compare the source types to determine if there's an
1741 // inheritance relationship in their sources.
1742 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1743 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1744
1745 // Adjust the types we're converting from via the array-to-pointer
1746 // conversion, if we need to.
1747 if (SCS1.First == ICK_Array_To_Pointer)
1748 FromType1 = Context.getArrayDecayedType(FromType1);
1749 if (SCS2.First == ICK_Array_To_Pointer)
1750 FromType2 = Context.getArrayDecayedType(FromType2);
1751
Douglas Gregor01919692009-12-13 21:37:05 +00001752 QualType FromPointee1
1753 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1754 QualType FromPointee2
1755 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001756
Douglas Gregor01919692009-12-13 21:37:05 +00001757 if (IsDerivedFrom(FromPointee2, FromPointee1))
1758 return ImplicitConversionSequence::Better;
1759 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1760 return ImplicitConversionSequence::Worse;
1761
1762 // Objective-C++: If one interface is more specific than the
1763 // other, it is the better one.
1764 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1765 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1766 if (FromIface1 && FromIface1) {
1767 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1768 return ImplicitConversionSequence::Better;
1769 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1770 return ImplicitConversionSequence::Worse;
1771 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001772 }
Douglas Gregor57373262008-10-22 14:17:15 +00001773
1774 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1775 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00001776 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001777 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001778 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001779
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001780 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001781 // C++0x [over.ics.rank]p3b4:
1782 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1783 // implicit object parameter of a non-static member function declared
1784 // without a ref-qualifier, and S1 binds an rvalue reference to an
1785 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00001786 // FIXME: We don't know if we're dealing with the implicit object parameter,
1787 // or if the member function in this case has a ref qualifier.
1788 // (Of course, we don't have ref qualifiers yet.)
1789 if (SCS1.RRefBinding != SCS2.RRefBinding)
1790 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1791 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001792
1793 // C++ [over.ics.rank]p3b4:
1794 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1795 // which the references refer are the same type except for
1796 // top-level cv-qualifiers, and the type to which the reference
1797 // initialized by S2 refers is more cv-qualified than the type
1798 // to which the reference initialized by S1 refers.
Sebastian Redla9845802009-03-29 15:27:50 +00001799 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1800 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001801 T1 = Context.getCanonicalType(T1);
1802 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00001803 Qualifiers T1Quals, T2Quals;
1804 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1805 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1806 if (UnqualT1 == UnqualT2) {
1807 // If the type is an array type, promote the element qualifiers to the type
1808 // for comparison.
1809 if (isa<ArrayType>(T1) && T1Quals)
1810 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1811 if (isa<ArrayType>(T2) && T2Quals)
1812 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001813 if (T2.isMoreQualifiedThan(T1))
1814 return ImplicitConversionSequence::Better;
1815 else if (T1.isMoreQualifiedThan(T2))
1816 return ImplicitConversionSequence::Worse;
1817 }
1818 }
Douglas Gregor57373262008-10-22 14:17:15 +00001819
1820 return ImplicitConversionSequence::Indistinguishable;
1821}
1822
1823/// CompareQualificationConversions - Compares two standard conversion
1824/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00001825/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1826ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00001827Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00001828 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00001829 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001830 // -- S1 and S2 differ only in their qualification conversion and
1831 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1832 // cv-qualification signature of type T1 is a proper subset of
1833 // the cv-qualification signature of type T2, and S1 is not the
1834 // deprecated string literal array-to-pointer conversion (4.2).
1835 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1836 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1837 return ImplicitConversionSequence::Indistinguishable;
1838
1839 // FIXME: the example in the standard doesn't use a qualification
1840 // conversion (!)
1841 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1842 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1843 T1 = Context.getCanonicalType(T1);
1844 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00001845 Qualifiers T1Quals, T2Quals;
1846 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1847 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00001848
1849 // If the types are the same, we won't learn anything by unwrapped
1850 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00001851 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00001852 return ImplicitConversionSequence::Indistinguishable;
1853
Chandler Carruth28e318c2009-12-29 07:16:59 +00001854 // If the type is an array type, promote the element qualifiers to the type
1855 // for comparison.
1856 if (isa<ArrayType>(T1) && T1Quals)
1857 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1858 if (isa<ArrayType>(T2) && T2Quals)
1859 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1860
Mike Stump1eb44332009-09-09 15:08:12 +00001861 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00001862 = ImplicitConversionSequence::Indistinguishable;
1863 while (UnwrapSimilarPointerTypes(T1, T2)) {
1864 // Within each iteration of the loop, we check the qualifiers to
1865 // determine if this still looks like a qualification
1866 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001867 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001868 // until there are no more pointers or pointers-to-members left
1869 // to unwrap. This essentially mimics what
1870 // IsQualificationConversion does, but here we're checking for a
1871 // strict subset of qualifiers.
1872 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1873 // The qualifiers are the same, so this doesn't tell us anything
1874 // about how the sequences rank.
1875 ;
1876 else if (T2.isMoreQualifiedThan(T1)) {
1877 // T1 has fewer qualifiers, so it could be the better sequence.
1878 if (Result == ImplicitConversionSequence::Worse)
1879 // Neither has qualifiers that are a subset of the other's
1880 // qualifiers.
1881 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001882
Douglas Gregor57373262008-10-22 14:17:15 +00001883 Result = ImplicitConversionSequence::Better;
1884 } else if (T1.isMoreQualifiedThan(T2)) {
1885 // T2 has fewer qualifiers, so it could be the better sequence.
1886 if (Result == ImplicitConversionSequence::Better)
1887 // Neither has qualifiers that are a subset of the other's
1888 // qualifiers.
1889 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001890
Douglas Gregor57373262008-10-22 14:17:15 +00001891 Result = ImplicitConversionSequence::Worse;
1892 } else {
1893 // Qualifiers are disjoint.
1894 return ImplicitConversionSequence::Indistinguishable;
1895 }
1896
1897 // If the types after this point are equivalent, we're done.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001898 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00001899 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001900 }
1901
Douglas Gregor57373262008-10-22 14:17:15 +00001902 // Check that the winning standard conversion sequence isn't using
1903 // the deprecated string literal array to pointer conversion.
1904 switch (Result) {
1905 case ImplicitConversionSequence::Better:
1906 if (SCS1.Deprecated)
1907 Result = ImplicitConversionSequence::Indistinguishable;
1908 break;
1909
1910 case ImplicitConversionSequence::Indistinguishable:
1911 break;
1912
1913 case ImplicitConversionSequence::Worse:
1914 if (SCS2.Deprecated)
1915 Result = ImplicitConversionSequence::Indistinguishable;
1916 break;
1917 }
1918
1919 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001920}
1921
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001922/// CompareDerivedToBaseConversions - Compares two standard conversion
1923/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001924/// various kinds of derived-to-base conversions (C++
1925/// [over.ics.rank]p4b3). As part of these checks, we also look at
1926/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001927ImplicitConversionSequence::CompareKind
1928Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1929 const StandardConversionSequence& SCS2) {
1930 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1931 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1932 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1933 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1934
1935 // Adjust the types we're converting from via the array-to-pointer
1936 // conversion, if we need to.
1937 if (SCS1.First == ICK_Array_To_Pointer)
1938 FromType1 = Context.getArrayDecayedType(FromType1);
1939 if (SCS2.First == ICK_Array_To_Pointer)
1940 FromType2 = Context.getArrayDecayedType(FromType2);
1941
1942 // Canonicalize all of the types.
1943 FromType1 = Context.getCanonicalType(FromType1);
1944 ToType1 = Context.getCanonicalType(ToType1);
1945 FromType2 = Context.getCanonicalType(FromType2);
1946 ToType2 = Context.getCanonicalType(ToType2);
1947
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001948 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001949 //
1950 // If class B is derived directly or indirectly from class A and
1951 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001952 //
1953 // For Objective-C, we let A, B, and C also be Objective-C
1954 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001955
1956 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00001957 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001958 SCS2.Second == ICK_Pointer_Conversion &&
1959 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1960 FromType1->isPointerType() && FromType2->isPointerType() &&
1961 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001962 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001963 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00001964 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001965 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001966 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001967 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001968 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001969 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001970
John McCall183700f2009-09-21 23:43:11 +00001971 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1972 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1973 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1974 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001975
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001976 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001977 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1978 if (IsDerivedFrom(ToPointee1, ToPointee2))
1979 return ImplicitConversionSequence::Better;
1980 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1981 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001982
1983 if (ToIface1 && ToIface2) {
1984 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1985 return ImplicitConversionSequence::Better;
1986 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1987 return ImplicitConversionSequence::Worse;
1988 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001989 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001990
1991 // -- conversion of B* to A* is better than conversion of C* to A*,
1992 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1993 if (IsDerivedFrom(FromPointee2, FromPointee1))
1994 return ImplicitConversionSequence::Better;
1995 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1996 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00001997
Douglas Gregorcb7de522008-11-26 23:31:11 +00001998 if (FromIface1 && FromIface2) {
1999 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2000 return ImplicitConversionSequence::Better;
2001 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2002 return ImplicitConversionSequence::Worse;
2003 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002004 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002005 }
2006
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002007 // Compare based on reference bindings.
2008 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
2009 SCS1.Second == ICK_Derived_To_Base) {
2010 // -- binding of an expression of type C to a reference of type
2011 // B& is better than binding an expression of type C to a
2012 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002013 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2014 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002015 if (IsDerivedFrom(ToType1, ToType2))
2016 return ImplicitConversionSequence::Better;
2017 else if (IsDerivedFrom(ToType2, ToType1))
2018 return ImplicitConversionSequence::Worse;
2019 }
2020
Douglas Gregor225c41e2008-11-03 19:09:14 +00002021 // -- binding of an expression of type B to a reference of type
2022 // A& is better than binding an expression of type C to a
2023 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002024 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2025 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002026 if (IsDerivedFrom(FromType2, FromType1))
2027 return ImplicitConversionSequence::Better;
2028 else if (IsDerivedFrom(FromType1, FromType2))
2029 return ImplicitConversionSequence::Worse;
2030 }
2031 }
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002032
2033 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002034 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2035 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2036 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2037 const MemberPointerType * FromMemPointer1 =
2038 FromType1->getAs<MemberPointerType>();
2039 const MemberPointerType * ToMemPointer1 =
2040 ToType1->getAs<MemberPointerType>();
2041 const MemberPointerType * FromMemPointer2 =
2042 FromType2->getAs<MemberPointerType>();
2043 const MemberPointerType * ToMemPointer2 =
2044 ToType2->getAs<MemberPointerType>();
2045 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2046 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2047 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2048 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2049 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2050 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2051 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2052 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002053 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002054 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2055 if (IsDerivedFrom(ToPointee1, ToPointee2))
2056 return ImplicitConversionSequence::Worse;
2057 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2058 return ImplicitConversionSequence::Better;
2059 }
2060 // conversion of B::* to C::* is better than conversion of A::* to C::*
2061 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2062 if (IsDerivedFrom(FromPointee1, FromPointee2))
2063 return ImplicitConversionSequence::Better;
2064 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2065 return ImplicitConversionSequence::Worse;
2066 }
2067 }
2068
Douglas Gregor225c41e2008-11-03 19:09:14 +00002069 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
2070 SCS1.Second == ICK_Derived_To_Base) {
2071 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002072 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2073 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002074 if (IsDerivedFrom(ToType1, ToType2))
2075 return ImplicitConversionSequence::Better;
2076 else if (IsDerivedFrom(ToType2, ToType1))
2077 return ImplicitConversionSequence::Worse;
2078 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002079
Douglas Gregor225c41e2008-11-03 19:09:14 +00002080 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002081 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2082 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002083 if (IsDerivedFrom(FromType2, FromType1))
2084 return ImplicitConversionSequence::Better;
2085 else if (IsDerivedFrom(FromType1, FromType2))
2086 return ImplicitConversionSequence::Worse;
2087 }
2088 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002089
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002090 return ImplicitConversionSequence::Indistinguishable;
2091}
2092
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002093/// TryCopyInitialization - Try to copy-initialize a value of type
2094/// ToType from the expression From. Return the implicit conversion
2095/// sequence required to pass this argument, which may be a bad
2096/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00002097/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redle2b68332009-04-12 17:16:29 +00002098/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2099/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00002100ImplicitConversionSequence
2101Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002102 bool SuppressUserConversions, bool ForceRValue,
2103 bool InOverloadResolution) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00002104 if (ToType->isReferenceType()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002105 ImplicitConversionSequence ICS;
Mike Stump1eb44332009-09-09 15:08:12 +00002106 CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00002107 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002108 SuppressUserConversions,
2109 /*AllowExplicit=*/false,
2110 ForceRValue,
2111 &ICS);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002112 return ICS;
2113 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002114 return TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002115 SuppressUserConversions,
2116 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002117 ForceRValue,
2118 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002119 }
2120}
2121
Sebastian Redle2b68332009-04-12 17:16:29 +00002122/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2123/// the expression @p From. Returns true (and emits a diagnostic) if there was
2124/// an error, returns false if the initialization succeeded. Elidable should
2125/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2126/// differently in C++0x for this case.
Mike Stump1eb44332009-09-09 15:08:12 +00002127bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00002128 AssignmentAction Action, bool Elidable) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002129 if (!getLangOptions().CPlusPlus) {
2130 // In C, argument passing is the same as performing an assignment.
2131 QualType FromType = From->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002132
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002133 AssignConvertType ConvTy =
2134 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00002135 if (ConvTy != Compatible &&
2136 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2137 ConvTy = Compatible;
Mike Stump1eb44332009-09-09 15:08:12 +00002138
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002139 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00002140 FromType, From, Action);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002141 }
Sebastian Redle2b68332009-04-12 17:16:29 +00002142
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002143 if (ToType->isReferenceType())
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002144 return CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00002145 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002146 /*SuppressUserConversions=*/false,
2147 /*AllowExplicit=*/false,
2148 /*ForceRValue=*/false);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002149
Douglas Gregor68647482009-12-16 03:45:30 +00002150 if (!PerformImplicitConversion(From, ToType, Action,
Sebastian Redle2b68332009-04-12 17:16:29 +00002151 /*AllowExplicit=*/false, Elidable))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002152 return false;
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002153 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian455acd92009-09-22 19:53:15 +00002154 return Diag(From->getSourceRange().getBegin(),
2155 diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +00002156 << ToType << From->getType() << Action << From->getSourceRange();
Fariborz Jahanian455acd92009-09-22 19:53:15 +00002157 return true;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002158}
2159
Douglas Gregor96176b32008-11-18 23:14:02 +00002160/// TryObjectArgumentInitialization - Try to initialize the object
2161/// parameter of the given member function (@c Method) from the
2162/// expression @p From.
2163ImplicitConversionSequence
John McCall701c89e2009-12-03 04:06:58 +00002164Sema::TryObjectArgumentInitialization(QualType FromType,
2165 CXXMethodDecl *Method,
2166 CXXRecordDecl *ActingContext) {
2167 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002168 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2169 // const volatile object.
2170 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2171 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2172 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00002173
2174 // Set up the conversion sequence as a "bad" conversion, to allow us
2175 // to exit early.
2176 ImplicitConversionSequence ICS;
2177 ICS.Standard.setAsIdentityConversion();
2178 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2179
2180 // We need to have an object of class type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002181 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00002182 FromType = PT->getPointeeType();
2183
2184 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002185
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002186 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00002187 // where X is the class of which the function is a member
2188 // (C++ [over.match.funcs]p4). However, when finding an implicit
2189 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00002190 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00002191 // (C++ [over.match.funcs]p5). We perform a simplified version of
2192 // reference binding here, that allows class rvalues to bind to
2193 // non-constant references.
2194
2195 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2196 // with the implicit object parameter (C++ [over.match.funcs]p5).
2197 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002198 if (ImplicitParamType.getCVRQualifiers()
2199 != FromTypeCanon.getLocalCVRQualifiers() &&
Douglas Gregorb1c2ea52009-11-05 00:07:36 +00002200 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon))
Douglas Gregor96176b32008-11-18 23:14:02 +00002201 return ICS;
2202
2203 // Check that we have either the same type or a derived type. It
2204 // affects the conversion rank.
2205 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002206 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor96176b32008-11-18 23:14:02 +00002207 ICS.Standard.Second = ICK_Identity;
2208 else if (IsDerivedFrom(FromType, ClassType))
2209 ICS.Standard.Second = ICK_Derived_To_Base;
2210 else
2211 return ICS;
2212
2213 // Success. Mark this as a reference binding.
2214 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2215 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2216 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2217 ICS.Standard.ReferenceBinding = true;
2218 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00002219 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002220 return ICS;
2221}
2222
2223/// PerformObjectArgumentInitialization - Perform initialization of
2224/// the implicit object parameter for the given Method with the given
2225/// expression.
2226bool
2227Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002228 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00002229 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00002230 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002231
Ted Kremenek6217b802009-07-29 21:53:49 +00002232 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002233 FromRecordType = PT->getPointeeType();
2234 DestType = Method->getThisType(Context);
2235 } else {
2236 FromRecordType = From->getType();
2237 DestType = ImplicitParamRecordType;
2238 }
2239
John McCall701c89e2009-12-03 04:06:58 +00002240 // Note that we always use the true parent context when performing
2241 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002242 ImplicitConversionSequence ICS
John McCall701c89e2009-12-03 04:06:58 +00002243 = TryObjectArgumentInitialization(From->getType(), Method,
2244 Method->getParent());
Douglas Gregor96176b32008-11-18 23:14:02 +00002245 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2246 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002247 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00002248 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002249
Douglas Gregor96176b32008-11-18 23:14:02 +00002250 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssona552f7c2009-05-01 18:34:30 +00002251 CheckDerivedToBaseConversion(FromRecordType,
2252 ImplicitParamRecordType,
Douglas Gregor96176b32008-11-18 23:14:02 +00002253 From->getSourceRange().getBegin(),
2254 From->getSourceRange()))
2255 return true;
2256
Mike Stump1eb44332009-09-09 15:08:12 +00002257 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson116b7d92009-08-07 18:45:49 +00002258 /*isLvalue=*/true);
Douglas Gregor96176b32008-11-18 23:14:02 +00002259 return false;
2260}
2261
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002262/// TryContextuallyConvertToBool - Attempt to contextually convert the
2263/// expression From to bool (C++0x [conv]p3).
2264ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump1eb44332009-09-09 15:08:12 +00002265 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002266 // FIXME: Are these flags correct?
2267 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00002268 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00002269 /*ForceRValue=*/false,
2270 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002271}
2272
2273/// PerformContextuallyConvertToBool - Perform a contextual conversion
2274/// of the expression From to bool (C++0x [conv]p3).
2275bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2276 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
Douglas Gregor68647482009-12-16 03:45:30 +00002277 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting))
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002278 return false;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002279
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002280 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002281 return Diag(From->getSourceRange().getBegin(),
2282 diag::err_typecheck_bool_condition)
2283 << From->getType() << From->getSourceRange();
2284 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002285}
2286
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002287/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00002288/// candidate functions, using the given function call arguments. If
2289/// @p SuppressUserConversions, then don't allow user-defined
2290/// conversions via constructors or conversion operators.
Sebastian Redle2b68332009-04-12 17:16:29 +00002291/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2292/// hacky way to implement the overloading rules for elidable copy
2293/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002294///
2295/// \para PartialOverloading true if we are performing "partial" overloading
2296/// based on an incomplete set of function arguments. This feature is used by
2297/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00002298void
2299Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002300 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002301 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00002302 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002303 bool ForceRValue,
2304 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00002305 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002306 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002307 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00002308 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00002309 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00002310
Douglas Gregor88a35142008-12-22 05:46:06 +00002311 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002312 if (!isa<CXXConstructorDecl>(Method)) {
2313 // If we get here, it's because we're calling a member function
2314 // that is named without a member access expression (e.g.,
2315 // "this->f") that was either written explicitly or created
2316 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00002317 // function, e.g., X::f(). We use an empty type for the implied
2318 // object argument (C++ [over.call.func]p3), and the acting context
2319 // is irrelevant.
2320 AddMethodCandidate(Method, Method->getParent(),
2321 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002322 SuppressUserConversions, ForceRValue);
2323 return;
2324 }
2325 // We treat a constructor like a non-member function, since its object
2326 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00002327 }
2328
Douglas Gregorfd476482009-11-13 23:59:09 +00002329 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00002330 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00002331
Douglas Gregor7edfb692009-11-23 12:27:39 +00002332 // Overload resolution is always an unevaluated context.
2333 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2334
Douglas Gregor66724ea2009-11-14 01:20:54 +00002335 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2336 // C++ [class.copy]p3:
2337 // A member function template is never instantiated to perform the copy
2338 // of a class object to an object of its class type.
2339 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2340 if (NumArgs == 1 &&
2341 Constructor->isCopyConstructorLikeSpecialization() &&
2342 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2343 return;
2344 }
2345
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002346 // Add this candidate
2347 CandidateSet.push_back(OverloadCandidate());
2348 OverloadCandidate& Candidate = CandidateSet.back();
2349 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00002350 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002351 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002352 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002353
2354 unsigned NumArgsInProto = Proto->getNumArgs();
2355
2356 // (C++ 13.3.2p2): A candidate function having fewer than m
2357 // parameters is viable only if it has an ellipsis in its parameter
2358 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00002359 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2360 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002361 Candidate.Viable = false;
2362 return;
2363 }
2364
2365 // (C++ 13.3.2p2): A candidate function having more than m parameters
2366 // is viable only if the (m+1)st parameter has a default argument
2367 // (8.3.6). For the purposes of overload resolution, the
2368 // parameter list is truncated on the right, so that there are
2369 // exactly m parameters.
2370 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002371 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002372 // Not enough arguments.
2373 Candidate.Viable = false;
2374 return;
2375 }
2376
2377 // Determine the implicit conversion sequences for each of the
2378 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002379 Candidate.Conversions.resize(NumArgs);
2380 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2381 if (ArgIdx < NumArgsInProto) {
2382 // (C++ 13.3.2p3): for F to be a viable function, there shall
2383 // exist for each argument an implicit conversion sequence
2384 // (13.3.3.1) that converts that argument to the corresponding
2385 // parameter of F.
2386 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002387 Candidate.Conversions[ArgIdx]
2388 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002389 SuppressUserConversions, ForceRValue,
2390 /*InOverloadResolution=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00002391 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002392 == ImplicitConversionSequence::BadConversion) {
Fariborz Jahanian99d6c442009-09-28 19:06:58 +00002393 // 13.3.3.1-p10 If several different sequences of conversions exist that
2394 // each convert the argument to the parameter type, the implicit conversion
2395 // sequence associated with the parameter is defined to be the unique conversion
2396 // sequence designated the ambiguous conversion sequence. For the purpose of
2397 // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2398 // conversion sequence is treated as a user-defined sequence that is
2399 // indistinguishable from any other user-defined conversion sequence
Fariborz Jahanian4a6a2b82009-09-29 17:31:54 +00002400 if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
Fariborz Jahanian99d6c442009-09-28 19:06:58 +00002401 Candidate.Conversions[ArgIdx].ConversionKind =
2402 ImplicitConversionSequence::UserDefinedConversion;
Fariborz Jahanian4a6a2b82009-09-29 17:31:54 +00002403 // Set the conversion function to one of them. As due to ambiguity,
2404 // they carry the same weight and is needed for overload resolution
2405 // later.
2406 Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2407 Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2408 }
Fariborz Jahanian99d6c442009-09-28 19:06:58 +00002409 else {
2410 Candidate.Viable = false;
2411 break;
2412 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002413 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002414 } else {
2415 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2416 // argument for which there is no corresponding parameter is
2417 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002418 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002419 = ImplicitConversionSequence::EllipsisConversion;
2420 }
2421 }
2422}
2423
Douglas Gregor063daf62009-03-13 18:40:31 +00002424/// \brief Add all of the function declarations in the given function set to
2425/// the overload canddiate set.
2426void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2427 Expr **Args, unsigned NumArgs,
2428 OverloadCandidateSet& CandidateSet,
2429 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00002430 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor063daf62009-03-13 18:40:31 +00002431 FEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00002432 F != FEnd; ++F) {
John McCall701c89e2009-12-03 04:06:58 +00002433 // FIXME: using declarations
Douglas Gregor3f396022009-09-28 04:47:19 +00002434 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2435 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2436 AddMethodCandidate(cast<CXXMethodDecl>(FD),
John McCall701c89e2009-12-03 04:06:58 +00002437 cast<CXXMethodDecl>(FD)->getParent(),
2438 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00002439 CandidateSet, SuppressUserConversions);
2440 else
2441 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2442 SuppressUserConversions);
2443 } else {
2444 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2445 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2446 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2447 AddMethodTemplateCandidate(FunTmpl,
John McCall701c89e2009-12-03 04:06:58 +00002448 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00002449 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00002450 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00002451 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00002452 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00002453 else
2454 AddTemplateOverloadCandidate(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00002455 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00002456 Args, NumArgs, CandidateSet,
2457 SuppressUserConversions);
2458 }
Douglas Gregor364e0212009-06-27 21:05:07 +00002459 }
Douglas Gregor063daf62009-03-13 18:40:31 +00002460}
2461
John McCall314be4e2009-11-17 07:50:12 +00002462/// AddMethodCandidate - Adds a named decl (which is some kind of
2463/// method) as a method candidate to the given overload set.
John McCall701c89e2009-12-03 04:06:58 +00002464void Sema::AddMethodCandidate(NamedDecl *Decl,
2465 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00002466 Expr **Args, unsigned NumArgs,
2467 OverloadCandidateSet& CandidateSet,
2468 bool SuppressUserConversions, bool ForceRValue) {
John McCall701c89e2009-12-03 04:06:58 +00002469 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00002470
2471 if (isa<UsingShadowDecl>(Decl))
2472 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2473
2474 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2475 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2476 "Expected a member function template");
John McCall701c89e2009-12-03 04:06:58 +00002477 AddMethodTemplateCandidate(TD, ActingContext, /*ExplicitArgs*/ 0,
2478 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00002479 CandidateSet,
2480 SuppressUserConversions,
2481 ForceRValue);
2482 } else {
John McCall701c89e2009-12-03 04:06:58 +00002483 AddMethodCandidate(cast<CXXMethodDecl>(Decl), ActingContext,
2484 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00002485 CandidateSet, SuppressUserConversions, ForceRValue);
2486 }
2487}
2488
Douglas Gregor96176b32008-11-18 23:14:02 +00002489/// AddMethodCandidate - Adds the given C++ member function to the set
2490/// of candidate functions, using the given function call arguments
2491/// and the object argument (@c Object). For example, in a call
2492/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2493/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2494/// allow user-defined conversions via constructors or conversion
Sebastian Redle2b68332009-04-12 17:16:29 +00002495/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2496/// a slightly hacky way to implement the overloading rules for elidable copy
2497/// initialization in C++0x (C++0x 12.8p15).
Mike Stump1eb44332009-09-09 15:08:12 +00002498void
John McCall701c89e2009-12-03 04:06:58 +00002499Sema::AddMethodCandidate(CXXMethodDecl *Method, CXXRecordDecl *ActingContext,
2500 QualType ObjectType, Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00002501 OverloadCandidateSet& CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00002502 bool SuppressUserConversions, bool ForceRValue) {
2503 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002504 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00002505 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002506 assert(!isa<CXXConstructorDecl>(Method) &&
2507 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00002508
Douglas Gregor3f396022009-09-28 04:47:19 +00002509 if (!CandidateSet.isNewCandidate(Method))
2510 return;
2511
Douglas Gregor7edfb692009-11-23 12:27:39 +00002512 // Overload resolution is always an unevaluated context.
2513 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2514
Douglas Gregor96176b32008-11-18 23:14:02 +00002515 // Add this candidate
2516 CandidateSet.push_back(OverloadCandidate());
2517 OverloadCandidate& Candidate = CandidateSet.back();
2518 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002519 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002520 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002521
2522 unsigned NumArgsInProto = Proto->getNumArgs();
2523
2524 // (C++ 13.3.2p2): A candidate function having fewer than m
2525 // parameters is viable only if it has an ellipsis in its parameter
2526 // list (8.3.5).
2527 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2528 Candidate.Viable = false;
2529 return;
2530 }
2531
2532 // (C++ 13.3.2p2): A candidate function having more than m parameters
2533 // is viable only if the (m+1)st parameter has a default argument
2534 // (8.3.6). For the purposes of overload resolution, the
2535 // parameter list is truncated on the right, so that there are
2536 // exactly m parameters.
2537 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2538 if (NumArgs < MinRequiredArgs) {
2539 // Not enough arguments.
2540 Candidate.Viable = false;
2541 return;
2542 }
2543
2544 Candidate.Viable = true;
2545 Candidate.Conversions.resize(NumArgs + 1);
2546
John McCall701c89e2009-12-03 04:06:58 +00002547 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00002548 // The implicit object argument is ignored.
2549 Candidate.IgnoreObjectArgument = true;
2550 else {
2551 // Determine the implicit conversion sequence for the object
2552 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00002553 Candidate.Conversions[0]
2554 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
Mike Stump1eb44332009-09-09 15:08:12 +00002555 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor88a35142008-12-22 05:46:06 +00002556 == ImplicitConversionSequence::BadConversion) {
2557 Candidate.Viable = false;
2558 return;
2559 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002560 }
2561
2562 // Determine the implicit conversion sequences for each of the
2563 // arguments.
2564 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2565 if (ArgIdx < NumArgsInProto) {
2566 // (C++ 13.3.2p3): for F to be a viable function, there shall
2567 // exist for each argument an implicit conversion sequence
2568 // (13.3.3.1) that converts that argument to the corresponding
2569 // parameter of F.
2570 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002571 Candidate.Conversions[ArgIdx + 1]
2572 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002573 SuppressUserConversions, ForceRValue,
Anders Carlsson08972922009-08-28 15:33:32 +00002574 /*InOverloadResolution=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00002575 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002576 == ImplicitConversionSequence::BadConversion) {
2577 Candidate.Viable = false;
2578 break;
2579 }
2580 } else {
2581 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2582 // argument for which there is no corresponding parameter is
2583 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002584 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002585 = ImplicitConversionSequence::EllipsisConversion;
2586 }
2587 }
2588}
2589
Douglas Gregor6b906862009-08-21 00:16:32 +00002590/// \brief Add a C++ member function template as a candidate to the candidate
2591/// set, using template argument deduction to produce an appropriate member
2592/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002593void
Douglas Gregor6b906862009-08-21 00:16:32 +00002594Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall701c89e2009-12-03 04:06:58 +00002595 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00002596 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00002597 QualType ObjectType,
2598 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002599 OverloadCandidateSet& CandidateSet,
2600 bool SuppressUserConversions,
2601 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002602 if (!CandidateSet.isNewCandidate(MethodTmpl))
2603 return;
2604
Douglas Gregor6b906862009-08-21 00:16:32 +00002605 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002606 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00002607 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002608 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00002609 // candidate functions in the usual way.113) A given name can refer to one
2610 // or more function templates and also to a set of overloaded non-template
2611 // functions. In such a case, the candidate functions generated from each
2612 // function template are combined with the set of non-template candidate
2613 // functions.
2614 TemplateDeductionInfo Info(Context);
2615 FunctionDecl *Specialization = 0;
2616 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00002617 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002618 Args, NumArgs, Specialization, Info)) {
2619 // FIXME: Record what happened with template argument deduction, so
2620 // that we can give the user a beautiful diagnostic.
2621 (void)Result;
2622 return;
2623 }
Mike Stump1eb44332009-09-09 15:08:12 +00002624
Douglas Gregor6b906862009-08-21 00:16:32 +00002625 // Add the function template specialization produced by template argument
2626 // deduction as a candidate.
2627 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00002628 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00002629 "Specialization is not a member function?");
John McCall701c89e2009-12-03 04:06:58 +00002630 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), ActingContext,
2631 ObjectType, Args, NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002632 CandidateSet, SuppressUserConversions, ForceRValue);
2633}
2634
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002635/// \brief Add a C++ function template specialization as a candidate
2636/// in the candidate set, using template argument deduction to produce
2637/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002638void
Douglas Gregore53060f2009-06-25 22:08:12 +00002639Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002640 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002641 Expr **Args, unsigned NumArgs,
2642 OverloadCandidateSet& CandidateSet,
2643 bool SuppressUserConversions,
2644 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002645 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2646 return;
2647
Douglas Gregore53060f2009-06-25 22:08:12 +00002648 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002649 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00002650 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002651 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00002652 // candidate functions in the usual way.113) A given name can refer to one
2653 // or more function templates and also to a set of overloaded non-template
2654 // functions. In such a case, the candidate functions generated from each
2655 // function template are combined with the set of non-template candidate
2656 // functions.
2657 TemplateDeductionInfo Info(Context);
2658 FunctionDecl *Specialization = 0;
2659 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00002660 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002661 Args, NumArgs, Specialization, Info)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002662 // FIXME: Record what happened with template argument deduction, so
2663 // that we can give the user a beautiful diagnostic.
John McCall578b69b2009-12-16 08:11:27 +00002664 (void) Result;
2665
2666 CandidateSet.push_back(OverloadCandidate());
2667 OverloadCandidate &Candidate = CandidateSet.back();
2668 Candidate.Function = FunctionTemplate->getTemplatedDecl();
2669 Candidate.Viable = false;
2670 Candidate.IsSurrogate = false;
2671 Candidate.IgnoreObjectArgument = false;
Douglas Gregore53060f2009-06-25 22:08:12 +00002672 return;
2673 }
Mike Stump1eb44332009-09-09 15:08:12 +00002674
Douglas Gregore53060f2009-06-25 22:08:12 +00002675 // Add the function template specialization produced by template argument
2676 // deduction as a candidate.
2677 assert(Specialization && "Missing function template specialization?");
2678 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2679 SuppressUserConversions, ForceRValue);
2680}
Mike Stump1eb44332009-09-09 15:08:12 +00002681
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002682/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00002683/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002684/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00002685/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002686/// (which may or may not be the same type as the type that the
2687/// conversion function produces).
2688void
2689Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall701c89e2009-12-03 04:06:58 +00002690 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002691 Expr *From, QualType ToType,
2692 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002693 assert(!Conversion->getDescribedFunctionTemplate() &&
2694 "Conversion function templates use AddTemplateConversionCandidate");
2695
Douglas Gregor3f396022009-09-28 04:47:19 +00002696 if (!CandidateSet.isNewCandidate(Conversion))
2697 return;
2698
Douglas Gregor7edfb692009-11-23 12:27:39 +00002699 // Overload resolution is always an unevaluated context.
2700 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2701
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002702 // Add this candidate
2703 CandidateSet.push_back(OverloadCandidate());
2704 OverloadCandidate& Candidate = CandidateSet.back();
2705 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002706 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002707 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002708 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump1eb44332009-09-09 15:08:12 +00002709 Candidate.FinalConversion.FromTypePtr
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002710 = Conversion->getConversionType().getAsOpaquePtr();
2711 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2712
Douglas Gregor96176b32008-11-18 23:14:02 +00002713 // Determine the implicit conversion sequence for the implicit
2714 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002715 Candidate.Viable = true;
2716 Candidate.Conversions.resize(1);
John McCall701c89e2009-12-03 04:06:58 +00002717 Candidate.Conversions[0]
2718 = TryObjectArgumentInitialization(From->getType(), Conversion,
2719 ActingContext);
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002720 // Conversion functions to a different type in the base class is visible in
2721 // the derived class. So, a derived to base conversion should not participate
2722 // in overload resolution.
2723 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2724 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump1eb44332009-09-09 15:08:12 +00002725 if (Candidate.Conversions[0].ConversionKind
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002726 == ImplicitConversionSequence::BadConversion) {
2727 Candidate.Viable = false;
2728 return;
2729 }
Fariborz Jahanian3759a032009-10-19 19:18:20 +00002730
2731 // We won't go through a user-define type conversion function to convert a
2732 // derived to base as such conversions are given Conversion Rank. They only
2733 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2734 QualType FromCanon
2735 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2736 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2737 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2738 Candidate.Viable = false;
2739 return;
2740 }
2741
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002742
2743 // To determine what the conversion from the result of calling the
2744 // conversion function to the type we're eventually trying to
2745 // convert to (ToType), we need to synthesize a call to the
2746 // conversion function and attempt copy initialization from it. This
2747 // makes sure that we get the right semantics with respect to
2748 // lvalues/rvalues and the type. Fortunately, we can allocate this
2749 // call on the stack and we don't need its arguments to be
2750 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00002751 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002752 From->getLocStart());
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002753 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman73c39ab2009-10-20 08:27:19 +00002754 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002755 &ConversionRef, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002756
2757 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00002758 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2759 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00002760 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002761 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002762 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00002763 ImplicitConversionSequence ICS =
2764 TryCopyInitialization(&Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002765 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002766 /*ForceRValue=*/false,
2767 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002768
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002769 switch (ICS.ConversionKind) {
2770 case ImplicitConversionSequence::StandardConversion:
2771 Candidate.FinalConversion = ICS.Standard;
2772 break;
2773
2774 case ImplicitConversionSequence::BadConversion:
2775 Candidate.Viable = false;
2776 break;
2777
2778 default:
Mike Stump1eb44332009-09-09 15:08:12 +00002779 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002780 "Can only end up with a standard conversion sequence or failure");
2781 }
2782}
2783
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002784/// \brief Adds a conversion function template specialization
2785/// candidate to the overload set, using template argument deduction
2786/// to deduce the template arguments of the conversion function
2787/// template from the type that we are converting to (C++
2788/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00002789void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002790Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall701c89e2009-12-03 04:06:58 +00002791 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002792 Expr *From, QualType ToType,
2793 OverloadCandidateSet &CandidateSet) {
2794 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2795 "Only conversion function templates permitted here");
2796
Douglas Gregor3f396022009-09-28 04:47:19 +00002797 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2798 return;
2799
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002800 TemplateDeductionInfo Info(Context);
2801 CXXConversionDecl *Specialization = 0;
2802 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00002803 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002804 Specialization, Info)) {
2805 // FIXME: Record what happened with template argument deduction, so
2806 // that we can give the user a beautiful diagnostic.
2807 (void)Result;
2808 return;
2809 }
Mike Stump1eb44332009-09-09 15:08:12 +00002810
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002811 // Add the conversion function template specialization produced by
2812 // template argument deduction as a candidate.
2813 assert(Specialization && "Missing function template specialization?");
John McCall701c89e2009-12-03 04:06:58 +00002814 AddConversionCandidate(Specialization, ActingDC, From, ToType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002815}
2816
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002817/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2818/// converts the given @c Object to a function pointer via the
2819/// conversion function @c Conversion, and then attempts to call it
2820/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2821/// the type of function that we'll eventually be calling.
2822void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall701c89e2009-12-03 04:06:58 +00002823 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00002824 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00002825 QualType ObjectType,
2826 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002827 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002828 if (!CandidateSet.isNewCandidate(Conversion))
2829 return;
2830
Douglas Gregor7edfb692009-11-23 12:27:39 +00002831 // Overload resolution is always an unevaluated context.
2832 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2833
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002834 CandidateSet.push_back(OverloadCandidate());
2835 OverloadCandidate& Candidate = CandidateSet.back();
2836 Candidate.Function = 0;
2837 Candidate.Surrogate = Conversion;
2838 Candidate.Viable = true;
2839 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002840 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002841 Candidate.Conversions.resize(NumArgs + 1);
2842
2843 // Determine the implicit conversion sequence for the implicit
2844 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00002845 ImplicitConversionSequence ObjectInit
John McCall701c89e2009-12-03 04:06:58 +00002846 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002847 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2848 Candidate.Viable = false;
2849 return;
2850 }
2851
2852 // The first conversion is actually a user-defined conversion whose
2853 // first conversion is ObjectInit's standard conversion (which is
2854 // effectively a reference binding). Record it as such.
Mike Stump1eb44332009-09-09 15:08:12 +00002855 Candidate.Conversions[0].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002856 = ImplicitConversionSequence::UserDefinedConversion;
2857 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002858 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002859 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00002860 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002861 = Candidate.Conversions[0].UserDefined.Before;
2862 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2863
Mike Stump1eb44332009-09-09 15:08:12 +00002864 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002865 unsigned NumArgsInProto = Proto->getNumArgs();
2866
2867 // (C++ 13.3.2p2): A candidate function having fewer than m
2868 // parameters is viable only if it has an ellipsis in its parameter
2869 // list (8.3.5).
2870 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2871 Candidate.Viable = false;
2872 return;
2873 }
2874
2875 // Function types don't have any default arguments, so just check if
2876 // we have enough arguments.
2877 if (NumArgs < NumArgsInProto) {
2878 // Not enough arguments.
2879 Candidate.Viable = false;
2880 return;
2881 }
2882
2883 // Determine the implicit conversion sequences for each of the
2884 // arguments.
2885 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2886 if (ArgIdx < NumArgsInProto) {
2887 // (C++ 13.3.2p3): for F to be a viable function, there shall
2888 // exist for each argument an implicit conversion sequence
2889 // (13.3.3.1) that converts that argument to the corresponding
2890 // parameter of F.
2891 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002892 Candidate.Conversions[ArgIdx + 1]
2893 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002894 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002895 /*ForceRValue=*/false,
2896 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002897 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002898 == ImplicitConversionSequence::BadConversion) {
2899 Candidate.Viable = false;
2900 break;
2901 }
2902 } else {
2903 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2904 // argument for which there is no corresponding parameter is
2905 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002906 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002907 = ImplicitConversionSequence::EllipsisConversion;
2908 }
2909 }
2910}
2911
Mike Stump390b4cc2009-05-16 07:39:55 +00002912// FIXME: This will eventually be removed, once we've migrated all of the
2913// operator overloading logic over to the scheme used by binary operators, which
2914// works for template instantiation.
Douglas Gregor063daf62009-03-13 18:40:31 +00002915void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002916 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00002917 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002918 OverloadCandidateSet& CandidateSet,
2919 SourceRange OpRange) {
Douglas Gregor063daf62009-03-13 18:40:31 +00002920 FunctionSet Functions;
2921
2922 QualType T1 = Args[0]->getType();
2923 QualType T2;
2924 if (NumArgs > 1)
2925 T2 = Args[1]->getType();
2926
2927 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002928 if (S)
2929 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redl644be852009-10-23 19:23:15 +00002930 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00002931 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2932 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002933 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00002934}
2935
2936/// \brief Add overload candidates for overloaded operators that are
2937/// member functions.
2938///
2939/// Add the overloaded operator candidates that are member functions
2940/// for the operator Op that was used in an operator expression such
2941/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2942/// CandidateSet will store the added overload candidates. (C++
2943/// [over.match.oper]).
2944void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2945 SourceLocation OpLoc,
2946 Expr **Args, unsigned NumArgs,
2947 OverloadCandidateSet& CandidateSet,
2948 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002949 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2950
2951 // C++ [over.match.oper]p3:
2952 // For a unary operator @ with an operand of a type whose
2953 // cv-unqualified version is T1, and for a binary operator @ with
2954 // a left operand of a type whose cv-unqualified version is T1 and
2955 // a right operand of a type whose cv-unqualified version is T2,
2956 // three sets of candidate functions, designated member
2957 // candidates, non-member candidates and built-in candidates, are
2958 // constructed as follows:
2959 QualType T1 = Args[0]->getType();
2960 QualType T2;
2961 if (NumArgs > 1)
2962 T2 = Args[1]->getType();
2963
2964 // -- If T1 is a class type, the set of member candidates is the
2965 // result of the qualified lookup of T1::operator@
2966 // (13.3.1.1.1); otherwise, the set of member candidates is
2967 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00002968 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002969 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00002970 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002971 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002972
John McCalla24dc2e2009-11-17 02:14:36 +00002973 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
2974 LookupQualifiedName(Operators, T1Rec->getDecl());
2975 Operators.suppressDiagnostics();
2976
Mike Stump1eb44332009-09-09 15:08:12 +00002977 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002978 OperEnd = Operators.end();
2979 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00002980 ++Oper)
John McCall701c89e2009-12-03 04:06:58 +00002981 AddMethodCandidate(*Oper, Args[0]->getType(),
2982 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00002983 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00002984 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002985}
2986
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002987/// AddBuiltinCandidate - Add a candidate for a built-in
2988/// operator. ResultTy and ParamTys are the result and parameter types
2989/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002990/// arguments being passed to the candidate. IsAssignmentOperator
2991/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002992/// operator. NumContextualBoolArguments is the number of arguments
2993/// (at the beginning of the argument list) that will be contextually
2994/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00002995void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002996 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002997 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002998 bool IsAssignmentOperator,
2999 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00003000 // Overload resolution is always an unevaluated context.
3001 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3002
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003003 // Add this candidate
3004 CandidateSet.push_back(OverloadCandidate());
3005 OverloadCandidate& Candidate = CandidateSet.back();
3006 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003007 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003008 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003009 Candidate.BuiltinTypes.ResultTy = ResultTy;
3010 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3011 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3012
3013 // Determine the implicit conversion sequences for each of the
3014 // arguments.
3015 Candidate.Viable = true;
3016 Candidate.Conversions.resize(NumArgs);
3017 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003018 // C++ [over.match.oper]p4:
3019 // For the built-in assignment operators, conversions of the
3020 // left operand are restricted as follows:
3021 // -- no temporaries are introduced to hold the left operand, and
3022 // -- no user-defined conversions are applied to the left
3023 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00003024 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003025 //
3026 // We block these conversions by turning off user-defined
3027 // conversions, since that is the only way that initialization of
3028 // a reference to a non-class type can occur from something that
3029 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003030 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00003031 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003032 "Contextual conversion to bool requires bool type");
3033 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3034 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003035 Candidate.Conversions[ArgIdx]
3036 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00003037 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003038 /*ForceRValue=*/false,
3039 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003040 }
Mike Stump1eb44332009-09-09 15:08:12 +00003041 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00003042 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003043 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003044 break;
3045 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003046 }
3047}
3048
3049/// BuiltinCandidateTypeSet - A set of types that will be used for the
3050/// candidate operator functions for built-in operators (C++
3051/// [over.built]). The types are separated into pointer types and
3052/// enumeration types.
3053class BuiltinCandidateTypeSet {
3054 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003055 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003056
3057 /// PointerTypes - The set of pointer types that will be used in the
3058 /// built-in candidates.
3059 TypeSet PointerTypes;
3060
Sebastian Redl78eb8742009-04-19 21:53:20 +00003061 /// MemberPointerTypes - The set of member pointer types that will be
3062 /// used in the built-in candidates.
3063 TypeSet MemberPointerTypes;
3064
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003065 /// EnumerationTypes - The set of enumeration types that will be
3066 /// used in the built-in candidates.
3067 TypeSet EnumerationTypes;
3068
Douglas Gregor5842ba92009-08-24 15:23:48 +00003069 /// Sema - The semantic analysis instance where we are building the
3070 /// candidate type set.
3071 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003072
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003073 /// Context - The AST context in which we will build the type sets.
3074 ASTContext &Context;
3075
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003076 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3077 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00003078 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003079
3080public:
3081 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003082 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003083
Mike Stump1eb44332009-09-09 15:08:12 +00003084 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00003085 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003086
Douglas Gregor573d9c32009-10-21 23:19:44 +00003087 void AddTypesConvertedFrom(QualType Ty,
3088 SourceLocation Loc,
3089 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003090 bool AllowExplicitConversions,
3091 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003092
3093 /// pointer_begin - First pointer type found;
3094 iterator pointer_begin() { return PointerTypes.begin(); }
3095
Sebastian Redl78eb8742009-04-19 21:53:20 +00003096 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003097 iterator pointer_end() { return PointerTypes.end(); }
3098
Sebastian Redl78eb8742009-04-19 21:53:20 +00003099 /// member_pointer_begin - First member pointer type found;
3100 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3101
3102 /// member_pointer_end - Past the last member pointer type found;
3103 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3104
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003105 /// enumeration_begin - First enumeration type found;
3106 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3107
Sebastian Redl78eb8742009-04-19 21:53:20 +00003108 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003109 iterator enumeration_end() { return EnumerationTypes.end(); }
3110};
3111
Sebastian Redl78eb8742009-04-19 21:53:20 +00003112/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003113/// the set of pointer types along with any more-qualified variants of
3114/// that type. For example, if @p Ty is "int const *", this routine
3115/// will add "int const *", "int const volatile *", "int const
3116/// restrict *", and "int const volatile restrict *" to the set of
3117/// pointer types. Returns true if the add of @p Ty itself succeeded,
3118/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003119///
3120/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003121bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00003122BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3123 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00003124
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003125 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003126 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003127 return false;
3128
John McCall0953e762009-09-24 19:53:00 +00003129 const PointerType *PointerTy = Ty->getAs<PointerType>();
3130 assert(PointerTy && "type was not a pointer type!");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003131
John McCall0953e762009-09-24 19:53:00 +00003132 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003133 // Don't add qualified variants of arrays. For one, they're not allowed
3134 // (the qualifier would sink to the element type), and for another, the
3135 // only overload situation where it matters is subscript or pointer +- int,
3136 // and those shouldn't have qualifier variants anyway.
3137 if (PointeeTy->isArrayType())
3138 return true;
John McCall0953e762009-09-24 19:53:00 +00003139 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00003140 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00003141 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003142 bool hasVolatile = VisibleQuals.hasVolatile();
3143 bool hasRestrict = VisibleQuals.hasRestrict();
3144
John McCall0953e762009-09-24 19:53:00 +00003145 // Iterate through all strict supersets of BaseCVR.
3146 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3147 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003148 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3149 // in the types.
3150 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3151 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00003152 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3153 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003154 }
3155
3156 return true;
3157}
3158
Sebastian Redl78eb8742009-04-19 21:53:20 +00003159/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3160/// to the set of pointer types along with any more-qualified variants of
3161/// that type. For example, if @p Ty is "int const *", this routine
3162/// will add "int const *", "int const volatile *", "int const
3163/// restrict *", and "int const volatile restrict *" to the set of
3164/// pointer types. Returns true if the add of @p Ty itself succeeded,
3165/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003166///
3167/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003168bool
3169BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3170 QualType Ty) {
3171 // Insert this type.
3172 if (!MemberPointerTypes.insert(Ty))
3173 return false;
3174
John McCall0953e762009-09-24 19:53:00 +00003175 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3176 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00003177
John McCall0953e762009-09-24 19:53:00 +00003178 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003179 // Don't add qualified variants of arrays. For one, they're not allowed
3180 // (the qualifier would sink to the element type), and for another, the
3181 // only overload situation where it matters is subscript or pointer +- int,
3182 // and those shouldn't have qualifier variants anyway.
3183 if (PointeeTy->isArrayType())
3184 return true;
John McCall0953e762009-09-24 19:53:00 +00003185 const Type *ClassTy = PointerTy->getClass();
3186
3187 // Iterate through all strict supersets of the pointee type's CVR
3188 // qualifiers.
3189 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3190 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3191 if ((CVR | BaseCVR) != CVR) continue;
3192
3193 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3194 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00003195 }
3196
3197 return true;
3198}
3199
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003200/// AddTypesConvertedFrom - Add each of the types to which the type @p
3201/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00003202/// primarily interested in pointer types and enumeration types. We also
3203/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003204/// AllowUserConversions is true if we should look at the conversion
3205/// functions of a class type, and AllowExplicitConversions if we
3206/// should also include the explicit conversion functions of a class
3207/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003208void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003209BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003210 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003211 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003212 bool AllowExplicitConversions,
3213 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003214 // Only deal with canonical types.
3215 Ty = Context.getCanonicalType(Ty);
3216
3217 // Look through reference types; they aren't part of the type of an
3218 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00003219 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003220 Ty = RefTy->getPointeeType();
3221
3222 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003223 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003224
Sebastian Redla65b5512009-11-05 16:36:20 +00003225 // If we're dealing with an array type, decay to the pointer.
3226 if (Ty->isArrayType())
3227 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3228
Ted Kremenek6217b802009-07-29 21:53:49 +00003229 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003230 QualType PointeeTy = PointerTy->getPointeeType();
3231
3232 // Insert our type, and its more-qualified variants, into the set
3233 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003234 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003235 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00003236 } else if (Ty->isMemberPointerType()) {
3237 // Member pointers are far easier, since the pointee can't be converted.
3238 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3239 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003240 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00003241 EnumerationTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003242 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003243 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003244 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003245 // No conversion functions in incomplete types.
3246 return;
3247 }
Mike Stump1eb44332009-09-09 15:08:12 +00003248
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003249 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallba135432009-11-21 08:51:07 +00003250 const UnresolvedSet *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00003251 = ClassDecl->getVisibleConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00003252 for (UnresolvedSet::iterator I = Conversions->begin(),
3253 E = Conversions->end(); I != E; ++I) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003254
Mike Stump1eb44332009-09-09 15:08:12 +00003255 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003256 // about which builtin types we can convert to.
John McCallba135432009-11-21 08:51:07 +00003257 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003258 continue;
3259
John McCallba135432009-11-21 08:51:07 +00003260 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003261 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003262 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003263 VisibleQuals);
3264 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003265 }
3266 }
3267 }
3268}
3269
Douglas Gregor19b7b152009-08-24 13:43:27 +00003270/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3271/// the volatile- and non-volatile-qualified assignment operators for the
3272/// given type to the candidate set.
3273static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3274 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00003275 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003276 unsigned NumArgs,
3277 OverloadCandidateSet &CandidateSet) {
3278 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00003279
Douglas Gregor19b7b152009-08-24 13:43:27 +00003280 // T& operator=(T&, T)
3281 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3282 ParamTypes[1] = T;
3283 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3284 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003285
Douglas Gregor19b7b152009-08-24 13:43:27 +00003286 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3287 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00003288 ParamTypes[0]
3289 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00003290 ParamTypes[1] = T;
3291 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00003292 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003293 }
3294}
Mike Stump1eb44332009-09-09 15:08:12 +00003295
Sebastian Redl9994a342009-10-25 17:03:50 +00003296/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3297/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003298static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3299 Qualifiers VRQuals;
3300 const RecordType *TyRec;
3301 if (const MemberPointerType *RHSMPType =
3302 ArgExpr->getType()->getAs<MemberPointerType>())
3303 TyRec = cast<RecordType>(RHSMPType->getClass());
3304 else
3305 TyRec = ArgExpr->getType()->getAs<RecordType>();
3306 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003307 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003308 VRQuals.addVolatile();
3309 VRQuals.addRestrict();
3310 return VRQuals;
3311 }
3312
3313 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallba135432009-11-21 08:51:07 +00003314 const UnresolvedSet *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00003315 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003316
John McCallba135432009-11-21 08:51:07 +00003317 for (UnresolvedSet::iterator I = Conversions->begin(),
3318 E = Conversions->end(); I != E; ++I) {
3319 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003320 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3321 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3322 CanTy = ResTypeRef->getPointeeType();
3323 // Need to go down the pointer/mempointer chain and add qualifiers
3324 // as see them.
3325 bool done = false;
3326 while (!done) {
3327 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3328 CanTy = ResTypePtr->getPointeeType();
3329 else if (const MemberPointerType *ResTypeMPtr =
3330 CanTy->getAs<MemberPointerType>())
3331 CanTy = ResTypeMPtr->getPointeeType();
3332 else
3333 done = true;
3334 if (CanTy.isVolatileQualified())
3335 VRQuals.addVolatile();
3336 if (CanTy.isRestrictQualified())
3337 VRQuals.addRestrict();
3338 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3339 return VRQuals;
3340 }
3341 }
3342 }
3343 return VRQuals;
3344}
3345
Douglas Gregor74253732008-11-19 15:42:04 +00003346/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3347/// operator overloads to the candidate set (C++ [over.built]), based
3348/// on the operator @p Op and the arguments given. For example, if the
3349/// operator is a binary '+', this routine might add "int
3350/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003351void
Mike Stump1eb44332009-09-09 15:08:12 +00003352Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003353 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00003354 Expr **Args, unsigned NumArgs,
3355 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003356 // The set of "promoted arithmetic types", which are the arithmetic
3357 // types are that preserved by promotion (C++ [over.built]p2). Note
3358 // that the first few of these types are the promoted integral
3359 // types; these types need to be first.
3360 // FIXME: What about complex?
3361 const unsigned FirstIntegralType = 0;
3362 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00003363 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003364 LastPromotedIntegralType = 13;
3365 const unsigned FirstPromotedArithmeticType = 7,
3366 LastPromotedArithmeticType = 16;
3367 const unsigned NumArithmeticTypes = 16;
3368 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00003369 Context.BoolTy, Context.CharTy, Context.WCharTy,
3370// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003371 Context.SignedCharTy, Context.ShortTy,
3372 Context.UnsignedCharTy, Context.UnsignedShortTy,
3373 Context.IntTy, Context.LongTy, Context.LongLongTy,
3374 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3375 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3376 };
Douglas Gregor652371a2009-10-21 22:01:30 +00003377 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3378 "Invalid first promoted integral type");
3379 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3380 == Context.UnsignedLongLongTy &&
3381 "Invalid last promoted integral type");
3382 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3383 "Invalid first promoted arithmetic type");
3384 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3385 == Context.LongDoubleTy &&
3386 "Invalid last promoted arithmetic type");
3387
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003388 // Find all of the types that the arguments can convert to, but only
3389 // if the operator we're looking at has built-in operator candidates
3390 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003391 Qualifiers VisibleTypeConversionsQuals;
3392 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003393 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3394 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3395
Douglas Gregor5842ba92009-08-24 15:23:48 +00003396 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003397 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3398 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00003399 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003400 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00003401 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003402 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor74253732008-11-19 15:42:04 +00003403 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003404 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregor573d9c32009-10-21 23:19:44 +00003405 OpLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003406 true,
3407 (Op == OO_Exclaim ||
3408 Op == OO_AmpAmp ||
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003409 Op == OO_PipePipe),
3410 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003411 }
3412
3413 bool isComparison = false;
3414 switch (Op) {
3415 case OO_None:
3416 case NUM_OVERLOADED_OPERATORS:
3417 assert(false && "Expected an overloaded operator");
3418 break;
3419
Douglas Gregor74253732008-11-19 15:42:04 +00003420 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00003421 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00003422 goto UnaryStar;
3423 else
3424 goto BinaryStar;
3425 break;
3426
3427 case OO_Plus: // '+' is either unary or binary
3428 if (NumArgs == 1)
3429 goto UnaryPlus;
3430 else
3431 goto BinaryPlus;
3432 break;
3433
3434 case OO_Minus: // '-' is either unary or binary
3435 if (NumArgs == 1)
3436 goto UnaryMinus;
3437 else
3438 goto BinaryMinus;
3439 break;
3440
3441 case OO_Amp: // '&' is either unary or binary
3442 if (NumArgs == 1)
3443 goto UnaryAmp;
3444 else
3445 goto BinaryAmp;
3446
3447 case OO_PlusPlus:
3448 case OO_MinusMinus:
3449 // C++ [over.built]p3:
3450 //
3451 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3452 // is either volatile or empty, there exist candidate operator
3453 // functions of the form
3454 //
3455 // VQ T& operator++(VQ T&);
3456 // T operator++(VQ T&, int);
3457 //
3458 // C++ [over.built]p4:
3459 //
3460 // For every pair (T, VQ), where T is an arithmetic type other
3461 // than bool, and VQ is either volatile or empty, there exist
3462 // candidate operator functions of the form
3463 //
3464 // VQ T& operator--(VQ T&);
3465 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00003466 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00003467 Arith < NumArithmeticTypes; ++Arith) {
3468 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00003469 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003470 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00003471
3472 // Non-volatile version.
3473 if (NumArgs == 1)
3474 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3475 else
3476 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003477 // heuristic to reduce number of builtin candidates in the set.
3478 // Add volatile version only if there are conversions to a volatile type.
3479 if (VisibleTypeConversionsQuals.hasVolatile()) {
3480 // Volatile version
3481 ParamTypes[0]
3482 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3483 if (NumArgs == 1)
3484 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3485 else
3486 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3487 }
Douglas Gregor74253732008-11-19 15:42:04 +00003488 }
3489
3490 // C++ [over.built]p5:
3491 //
3492 // For every pair (T, VQ), where T is a cv-qualified or
3493 // cv-unqualified object type, and VQ is either volatile or
3494 // empty, there exist candidate operator functions of the form
3495 //
3496 // T*VQ& operator++(T*VQ&);
3497 // T*VQ& operator--(T*VQ&);
3498 // T* operator++(T*VQ&, int);
3499 // T* operator--(T*VQ&, int);
3500 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3501 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3502 // Skip pointer types that aren't pointers to object types.
Ted Kremenek6217b802009-07-29 21:53:49 +00003503 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00003504 continue;
3505
Mike Stump1eb44332009-09-09 15:08:12 +00003506 QualType ParamTypes[2] = {
3507 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00003508 };
Mike Stump1eb44332009-09-09 15:08:12 +00003509
Douglas Gregor74253732008-11-19 15:42:04 +00003510 // Without volatile
3511 if (NumArgs == 1)
3512 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3513 else
3514 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3515
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003516 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3517 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003518 // With volatile
John McCall0953e762009-09-24 19:53:00 +00003519 ParamTypes[0]
3520 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00003521 if (NumArgs == 1)
3522 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3523 else
3524 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3525 }
3526 }
3527 break;
3528
3529 UnaryStar:
3530 // C++ [over.built]p6:
3531 // For every cv-qualified or cv-unqualified object type T, there
3532 // exist candidate operator functions of the form
3533 //
3534 // T& operator*(T*);
3535 //
3536 // C++ [over.built]p7:
3537 // For every function type T, there exist candidate operator
3538 // functions of the form
3539 // T& operator*(T*);
3540 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3541 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3542 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00003543 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003544 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00003545 &ParamTy, Args, 1, CandidateSet);
3546 }
3547 break;
3548
3549 UnaryPlus:
3550 // C++ [over.built]p8:
3551 // For every type T, there exist candidate operator functions of
3552 // the form
3553 //
3554 // T* operator+(T*);
3555 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3556 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3557 QualType ParamTy = *Ptr;
3558 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3559 }
Mike Stump1eb44332009-09-09 15:08:12 +00003560
Douglas Gregor74253732008-11-19 15:42:04 +00003561 // Fall through
3562
3563 UnaryMinus:
3564 // C++ [over.built]p9:
3565 // For every promoted arithmetic type T, there exist candidate
3566 // operator functions of the form
3567 //
3568 // T operator+(T);
3569 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003570 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00003571 Arith < LastPromotedArithmeticType; ++Arith) {
3572 QualType ArithTy = ArithmeticTypes[Arith];
3573 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3574 }
3575 break;
3576
3577 case OO_Tilde:
3578 // C++ [over.built]p10:
3579 // For every promoted integral type T, there exist candidate
3580 // operator functions of the form
3581 //
3582 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003583 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00003584 Int < LastPromotedIntegralType; ++Int) {
3585 QualType IntTy = ArithmeticTypes[Int];
3586 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3587 }
3588 break;
3589
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003590 case OO_New:
3591 case OO_Delete:
3592 case OO_Array_New:
3593 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003594 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00003595 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003596 break;
3597
3598 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00003599 UnaryAmp:
3600 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003601 // C++ [over.match.oper]p3:
3602 // -- For the operator ',', the unary operator '&', or the
3603 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003604 break;
3605
Douglas Gregor19b7b152009-08-24 13:43:27 +00003606 case OO_EqualEqual:
3607 case OO_ExclaimEqual:
3608 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00003609 // For every pointer to member type T, there exist candidate operator
3610 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00003611 //
3612 // bool operator==(T,T);
3613 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00003614 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00003615 MemPtr = CandidateTypes.member_pointer_begin(),
3616 MemPtrEnd = CandidateTypes.member_pointer_end();
3617 MemPtr != MemPtrEnd;
3618 ++MemPtr) {
3619 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3620 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3621 }
Mike Stump1eb44332009-09-09 15:08:12 +00003622
Douglas Gregor19b7b152009-08-24 13:43:27 +00003623 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00003624
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003625 case OO_Less:
3626 case OO_Greater:
3627 case OO_LessEqual:
3628 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003629 // C++ [over.built]p15:
3630 //
3631 // For every pointer or enumeration type T, there exist
3632 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003633 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003634 // bool operator<(T, T);
3635 // bool operator>(T, T);
3636 // bool operator<=(T, T);
3637 // bool operator>=(T, T);
3638 // bool operator==(T, T);
3639 // bool operator!=(T, T);
3640 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3641 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3642 QualType ParamTypes[2] = { *Ptr, *Ptr };
3643 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3644 }
Mike Stump1eb44332009-09-09 15:08:12 +00003645 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003646 = CandidateTypes.enumeration_begin();
3647 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3648 QualType ParamTypes[2] = { *Enum, *Enum };
3649 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3650 }
3651
3652 // Fall through.
3653 isComparison = true;
3654
Douglas Gregor74253732008-11-19 15:42:04 +00003655 BinaryPlus:
3656 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003657 if (!isComparison) {
3658 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3659
3660 // C++ [over.built]p13:
3661 //
3662 // For every cv-qualified or cv-unqualified object type T
3663 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003664 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003665 // T* operator+(T*, ptrdiff_t);
3666 // T& operator[](T*, ptrdiff_t); [BELOW]
3667 // T* operator-(T*, ptrdiff_t);
3668 // T* operator+(ptrdiff_t, T*);
3669 // T& operator[](ptrdiff_t, T*); [BELOW]
3670 //
3671 // C++ [over.built]p14:
3672 //
3673 // For every T, where T is a pointer to object type, there
3674 // exist candidate operator functions of the form
3675 //
3676 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00003677 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003678 = CandidateTypes.pointer_begin();
3679 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3680 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3681
3682 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3683 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3684
3685 if (Op == OO_Plus) {
3686 // T* operator+(ptrdiff_t, T*);
3687 ParamTypes[0] = ParamTypes[1];
3688 ParamTypes[1] = *Ptr;
3689 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3690 } else {
3691 // ptrdiff_t operator-(T, T);
3692 ParamTypes[1] = *Ptr;
3693 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3694 Args, 2, CandidateSet);
3695 }
3696 }
3697 }
3698 // Fall through
3699
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003700 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00003701 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003702 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003703 // C++ [over.built]p12:
3704 //
3705 // For every pair of promoted arithmetic types L and R, there
3706 // exist candidate operator functions of the form
3707 //
3708 // LR operator*(L, R);
3709 // LR operator/(L, R);
3710 // LR operator+(L, R);
3711 // LR operator-(L, R);
3712 // bool operator<(L, R);
3713 // bool operator>(L, R);
3714 // bool operator<=(L, R);
3715 // bool operator>=(L, R);
3716 // bool operator==(L, R);
3717 // bool operator!=(L, R);
3718 //
3719 // where LR is the result of the usual arithmetic conversions
3720 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003721 //
3722 // C++ [over.built]p24:
3723 //
3724 // For every pair of promoted arithmetic types L and R, there exist
3725 // candidate operator functions of the form
3726 //
3727 // LR operator?(bool, L, R);
3728 //
3729 // where LR is the result of the usual arithmetic conversions
3730 // between types L and R.
3731 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003732 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003733 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003734 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003735 Right < LastPromotedArithmeticType; ++Right) {
3736 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00003737 QualType Result
3738 = isComparison
3739 ? Context.BoolTy
3740 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003741 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3742 }
3743 }
3744 break;
3745
3746 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00003747 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003748 case OO_Caret:
3749 case OO_Pipe:
3750 case OO_LessLess:
3751 case OO_GreaterGreater:
3752 // C++ [over.built]p17:
3753 //
3754 // For every pair of promoted integral types L and R, there
3755 // exist candidate operator functions of the form
3756 //
3757 // LR operator%(L, R);
3758 // LR operator&(L, R);
3759 // LR operator^(L, R);
3760 // LR operator|(L, R);
3761 // L operator<<(L, R);
3762 // L operator>>(L, R);
3763 //
3764 // where LR is the result of the usual arithmetic conversions
3765 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00003766 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003767 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003768 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003769 Right < LastPromotedIntegralType; ++Right) {
3770 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3771 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3772 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00003773 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003774 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3775 }
3776 }
3777 break;
3778
3779 case OO_Equal:
3780 // C++ [over.built]p20:
3781 //
3782 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00003783 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003784 // empty, there exist candidate operator functions of the form
3785 //
3786 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003787 for (BuiltinCandidateTypeSet::iterator
3788 Enum = CandidateTypes.enumeration_begin(),
3789 EnumEnd = CandidateTypes.enumeration_end();
3790 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00003791 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003792 CandidateSet);
3793 for (BuiltinCandidateTypeSet::iterator
3794 MemPtr = CandidateTypes.member_pointer_begin(),
3795 MemPtrEnd = CandidateTypes.member_pointer_end();
3796 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00003797 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003798 CandidateSet);
3799 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003800
3801 case OO_PlusEqual:
3802 case OO_MinusEqual:
3803 // C++ [over.built]p19:
3804 //
3805 // For every pair (T, VQ), where T is any type and VQ is either
3806 // volatile or empty, there exist candidate operator functions
3807 // of the form
3808 //
3809 // T*VQ& operator=(T*VQ&, T*);
3810 //
3811 // C++ [over.built]p21:
3812 //
3813 // For every pair (T, VQ), where T is a cv-qualified or
3814 // cv-unqualified object type and VQ is either volatile or
3815 // empty, there exist candidate operator functions of the form
3816 //
3817 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3818 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3819 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3820 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3821 QualType ParamTypes[2];
3822 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3823
3824 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003825 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003826 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3827 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003828
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003829 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3830 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003831 // volatile version
John McCall0953e762009-09-24 19:53:00 +00003832 ParamTypes[0]
3833 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003834 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3835 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003836 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003837 }
3838 // Fall through.
3839
3840 case OO_StarEqual:
3841 case OO_SlashEqual:
3842 // C++ [over.built]p18:
3843 //
3844 // For every triple (L, VQ, R), where L is an arithmetic type,
3845 // VQ is either volatile or empty, and R is a promoted
3846 // arithmetic type, there exist candidate operator functions of
3847 // the form
3848 //
3849 // VQ L& operator=(VQ L&, R);
3850 // VQ L& operator*=(VQ L&, R);
3851 // VQ L& operator/=(VQ L&, R);
3852 // VQ L& operator+=(VQ L&, R);
3853 // VQ L& operator-=(VQ L&, R);
3854 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003855 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003856 Right < LastPromotedArithmeticType; ++Right) {
3857 QualType ParamTypes[2];
3858 ParamTypes[1] = ArithmeticTypes[Right];
3859
3860 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003861 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003862 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3863 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003864
3865 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003866 if (VisibleTypeConversionsQuals.hasVolatile()) {
3867 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3868 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3869 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3870 /*IsAssigmentOperator=*/Op == OO_Equal);
3871 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003872 }
3873 }
3874 break;
3875
3876 case OO_PercentEqual:
3877 case OO_LessLessEqual:
3878 case OO_GreaterGreaterEqual:
3879 case OO_AmpEqual:
3880 case OO_CaretEqual:
3881 case OO_PipeEqual:
3882 // C++ [over.built]p22:
3883 //
3884 // For every triple (L, VQ, R), where L is an integral type, VQ
3885 // is either volatile or empty, and R is a promoted integral
3886 // type, there exist candidate operator functions of the form
3887 //
3888 // VQ L& operator%=(VQ L&, R);
3889 // VQ L& operator<<=(VQ L&, R);
3890 // VQ L& operator>>=(VQ L&, R);
3891 // VQ L& operator&=(VQ L&, R);
3892 // VQ L& operator^=(VQ L&, R);
3893 // VQ L& operator|=(VQ L&, R);
3894 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003895 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003896 Right < LastPromotedIntegralType; ++Right) {
3897 QualType ParamTypes[2];
3898 ParamTypes[1] = ArithmeticTypes[Right];
3899
3900 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003901 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003902 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00003903 if (VisibleTypeConversionsQuals.hasVolatile()) {
3904 // Add this built-in operator as a candidate (VQ is 'volatile').
3905 ParamTypes[0] = ArithmeticTypes[Left];
3906 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3907 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3908 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3909 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003910 }
3911 }
3912 break;
3913
Douglas Gregor74253732008-11-19 15:42:04 +00003914 case OO_Exclaim: {
3915 // C++ [over.operator]p23:
3916 //
3917 // There also exist candidate operator functions of the form
3918 //
Mike Stump1eb44332009-09-09 15:08:12 +00003919 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00003920 // bool operator&&(bool, bool); [BELOW]
3921 // bool operator||(bool, bool); [BELOW]
3922 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003923 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3924 /*IsAssignmentOperator=*/false,
3925 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00003926 break;
3927 }
3928
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003929 case OO_AmpAmp:
3930 case OO_PipePipe: {
3931 // C++ [over.operator]p23:
3932 //
3933 // There also exist candidate operator functions of the form
3934 //
Douglas Gregor74253732008-11-19 15:42:04 +00003935 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003936 // bool operator&&(bool, bool);
3937 // bool operator||(bool, bool);
3938 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003939 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3940 /*IsAssignmentOperator=*/false,
3941 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003942 break;
3943 }
3944
3945 case OO_Subscript:
3946 // C++ [over.built]p13:
3947 //
3948 // For every cv-qualified or cv-unqualified object type T there
3949 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003950 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003951 // T* operator+(T*, ptrdiff_t); [ABOVE]
3952 // T& operator[](T*, ptrdiff_t);
3953 // T* operator-(T*, ptrdiff_t); [ABOVE]
3954 // T* operator+(ptrdiff_t, T*); [ABOVE]
3955 // T& operator[](ptrdiff_t, T*);
3956 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3957 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3958 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00003959 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003960 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003961
3962 // T& operator[](T*, ptrdiff_t)
3963 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3964
3965 // T& operator[](ptrdiff_t, T*);
3966 ParamTypes[0] = ParamTypes[1];
3967 ParamTypes[1] = *Ptr;
3968 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3969 }
3970 break;
3971
3972 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003973 // C++ [over.built]p11:
3974 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3975 // C1 is the same type as C2 or is a derived class of C2, T is an object
3976 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3977 // there exist candidate operator functions of the form
3978 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3979 // where CV12 is the union of CV1 and CV2.
3980 {
3981 for (BuiltinCandidateTypeSet::iterator Ptr =
3982 CandidateTypes.pointer_begin();
3983 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3984 QualType C1Ty = (*Ptr);
3985 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00003986 QualifierCollector Q1;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003987 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00003988 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003989 if (!isa<RecordType>(C1))
3990 continue;
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003991 // heuristic to reduce number of builtin candidates in the set.
3992 // Add volatile/restrict version only if there are conversions to a
3993 // volatile/restrict type.
3994 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3995 continue;
3996 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3997 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003998 }
3999 for (BuiltinCandidateTypeSet::iterator
4000 MemPtr = CandidateTypes.member_pointer_begin(),
4001 MemPtrEnd = CandidateTypes.member_pointer_end();
4002 MemPtr != MemPtrEnd; ++MemPtr) {
4003 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4004 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00004005 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004006 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4007 break;
4008 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4009 // build CV12 T&
4010 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004011 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4012 T.isVolatileQualified())
4013 continue;
4014 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4015 T.isRestrictQualified())
4016 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004017 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004018 QualType ResultTy = Context.getLValueReferenceType(T);
4019 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4020 }
4021 }
4022 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004023 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004024
4025 case OO_Conditional:
4026 // Note that we don't consider the first argument, since it has been
4027 // contextually converted to bool long ago. The candidates below are
4028 // therefore added as binary.
4029 //
4030 // C++ [over.built]p24:
4031 // For every type T, where T is a pointer or pointer-to-member type,
4032 // there exist candidate operator functions of the form
4033 //
4034 // T operator?(bool, T, T);
4035 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004036 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4037 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4038 QualType ParamTypes[2] = { *Ptr, *Ptr };
4039 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4040 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00004041 for (BuiltinCandidateTypeSet::iterator Ptr =
4042 CandidateTypes.member_pointer_begin(),
4043 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4044 QualType ParamTypes[2] = { *Ptr, *Ptr };
4045 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4046 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004047 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004048 }
4049}
4050
Douglas Gregorfa047642009-02-04 00:32:51 +00004051/// \brief Add function candidates found via argument-dependent lookup
4052/// to the set of overloading candidates.
4053///
4054/// This routine performs argument-dependent name lookup based on the
4055/// given function name (which may also be an operator name) and adds
4056/// all of the overload candidates found by ADL to the overload
4057/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00004058void
Douglas Gregorfa047642009-02-04 00:32:51 +00004059Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
4060 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00004061 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004062 OverloadCandidateSet& CandidateSet,
4063 bool PartialOverloading) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004064 FunctionSet Functions;
Douglas Gregorfa047642009-02-04 00:32:51 +00004065
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004066 // FIXME: Should we be trafficking in canonical function decls throughout?
4067
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004068 // Record all of the function candidates that we've already
4069 // added to the overload set, so that we don't add those same
4070 // candidates a second time.
4071 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4072 CandEnd = CandidateSet.end();
4073 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00004074 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004075 Functions.insert(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00004076 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4077 Functions.insert(FunTmpl);
4078 }
Douglas Gregorfa047642009-02-04 00:32:51 +00004079
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004080 // FIXME: Pass in the explicit template arguments?
Sebastian Redl644be852009-10-23 19:23:15 +00004081 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregorfa047642009-02-04 00:32:51 +00004082
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004083 // Erase all of the candidates we already knew about.
4084 // FIXME: This is suboptimal. Is there a better way?
4085 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4086 CandEnd = CandidateSet.end();
4087 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00004088 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004089 Functions.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00004090 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4091 Functions.erase(FunTmpl);
4092 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004093
4094 // For each of the ADL candidates we found, add it to the overload
4095 // set.
4096 for (FunctionSet::iterator Func = Functions.begin(),
4097 FuncEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00004098 Func != FuncEnd; ++Func) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004099 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
John McCalld5532b62009-11-23 01:53:49 +00004100 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004101 continue;
4102
4103 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
4104 false, false, PartialOverloading);
4105 } else
Mike Stump1eb44332009-09-09 15:08:12 +00004106 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004107 ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004108 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00004109 }
Douglas Gregorfa047642009-02-04 00:32:51 +00004110}
4111
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004112/// isBetterOverloadCandidate - Determines whether the first overload
4113/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00004114bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004115Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump1eb44332009-09-09 15:08:12 +00004116 const OverloadCandidate& Cand2) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004117 // Define viable functions to be better candidates than non-viable
4118 // functions.
4119 if (!Cand2.Viable)
4120 return Cand1.Viable;
4121 else if (!Cand1.Viable)
4122 return false;
4123
Douglas Gregor88a35142008-12-22 05:46:06 +00004124 // C++ [over.match.best]p1:
4125 //
4126 // -- if F is a static member function, ICS1(F) is defined such
4127 // that ICS1(F) is neither better nor worse than ICS1(G) for
4128 // any function G, and, symmetrically, ICS1(G) is neither
4129 // better nor worse than ICS1(F).
4130 unsigned StartArg = 0;
4131 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4132 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004133
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004134 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00004135 // A viable function F1 is defined to be a better function than another
4136 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004137 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004138 unsigned NumArgs = Cand1.Conversions.size();
4139 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4140 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004141 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004142 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4143 Cand2.Conversions[ArgIdx])) {
4144 case ImplicitConversionSequence::Better:
4145 // Cand1 has a better conversion sequence.
4146 HasBetterConversion = true;
4147 break;
4148
4149 case ImplicitConversionSequence::Worse:
4150 // Cand1 can't be better than Cand2.
4151 return false;
4152
4153 case ImplicitConversionSequence::Indistinguishable:
4154 // Do nothing.
4155 break;
4156 }
4157 }
4158
Mike Stump1eb44332009-09-09 15:08:12 +00004159 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004160 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004161 if (HasBetterConversion)
4162 return true;
4163
Mike Stump1eb44332009-09-09 15:08:12 +00004164 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004165 // specialization, or, if not that,
4166 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4167 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4168 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004169
4170 // -- F1 and F2 are function template specializations, and the function
4171 // template for F1 is more specialized than the template for F2
4172 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004173 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00004174 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4175 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004176 if (FunctionTemplateDecl *BetterTemplate
4177 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4178 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor5d7d3752009-09-14 23:02:14 +00004179 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4180 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004181 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004182
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004183 // -- the context is an initialization by user-defined conversion
4184 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4185 // from the return type of F1 to the destination type (i.e.,
4186 // the type of the entity being initialized) is a better
4187 // conversion sequence than the standard conversion sequence
4188 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00004189 if (Cand1.Function && Cand2.Function &&
4190 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004191 isa<CXXConversionDecl>(Cand2.Function)) {
4192 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4193 Cand2.FinalConversion)) {
4194 case ImplicitConversionSequence::Better:
4195 // Cand1 has a better conversion sequence.
4196 return true;
4197
4198 case ImplicitConversionSequence::Worse:
4199 // Cand1 can't be better than Cand2.
4200 return false;
4201
4202 case ImplicitConversionSequence::Indistinguishable:
4203 // Do nothing
4204 break;
4205 }
4206 }
4207
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004208 return false;
4209}
4210
Mike Stump1eb44332009-09-09 15:08:12 +00004211/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00004212/// within an overload candidate set.
4213///
4214/// \param CandidateSet the set of candidate functions.
4215///
4216/// \param Loc the location of the function name (or operator symbol) for
4217/// which overload resolution occurs.
4218///
Mike Stump1eb44332009-09-09 15:08:12 +00004219/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00004220/// function, Best points to the candidate function found.
4221///
4222/// \returns The result of overload resolution.
Douglas Gregor20093b42009-12-09 23:02:17 +00004223OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4224 SourceLocation Loc,
4225 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004226 // Find the best viable function.
4227 Best = CandidateSet.end();
4228 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4229 Cand != CandidateSet.end(); ++Cand) {
4230 if (Cand->Viable) {
4231 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4232 Best = Cand;
4233 }
4234 }
4235
4236 // If we didn't find any viable functions, abort.
4237 if (Best == CandidateSet.end())
4238 return OR_No_Viable_Function;
4239
4240 // Make sure that this function is better than every other viable
4241 // function. If not, we have an ambiguity.
4242 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4243 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00004244 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004245 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004246 !isBetterOverloadCandidate(*Best, *Cand)) {
4247 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004248 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004249 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004250 }
Mike Stump1eb44332009-09-09 15:08:12 +00004251
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004252 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004253 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00004254 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004255 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004256 return OR_Deleted;
4257
Douglas Gregore0762c92009-06-19 23:52:42 +00004258 // C++ [basic.def.odr]p2:
4259 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00004260 // when referred to from a potentially-evaluated expression. [Note: this
4261 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00004262 // (clause 13), user-defined conversions (12.3.2), allocation function for
4263 // placement new (5.3.4), as well as non-default initialization (8.5).
4264 if (Best->Function)
4265 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004266 return OR_Success;
4267}
4268
John McCallb1622a12010-01-06 09:43:14 +00004269/// Notes the location of an overload candidate.
4270void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
4271
4272 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
4273 // At least call it a 'constructor'.
4274 if (!Ctor->isImplicit()) {
4275 Diag(Ctor->getLocation(), diag::note_ovl_candidate_ctor);
4276 return;
4277 }
4278
4279 CXXRecordDecl *Record = Ctor->getParent();
4280 if (Ctor->isCopyConstructor()) {
4281 Diag(Record->getLocation(), diag::note_ovl_candidate_implicit_copy_ctor);
4282 return;
4283 }
4284
4285 Diag(Record->getLocation(), diag::note_ovl_candidate_implicit_default_ctor);
4286 return;
4287 }
4288
4289 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4290 // This actually gets spelled 'candidate function' for now, but
4291 // it doesn't hurt to split it out.
4292 if (!Meth->isImplicit()) {
4293 Diag(Meth->getLocation(), diag::note_ovl_candidate_meth);
4294 return;
4295 }
4296
4297 assert(Meth->isCopyAssignment()
4298 && "implicit method is not copy assignment operator?");
4299 Diag(Meth->getParent()->getLocation(),
4300 diag::note_ovl_candidate_implicit_copy_assign);
4301 return;
4302 }
4303
4304 Diag(Fn->getLocation(), diag::note_ovl_candidate);
4305}
4306
John McCalla1d7d622010-01-08 00:58:21 +00004307namespace {
4308
John McCall81201622010-01-08 04:41:39 +00004309void NoteDeletedCandidate(Sema &S, OverloadCandidate *Cand) {
4310}
4311
John McCalla1d7d622010-01-08 00:58:21 +00004312void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand) {
John McCall81201622010-01-08 04:41:39 +00004313 // Note deleted candidates, but only if they're viable.
4314 if (Cand->Viable &&
4315 (Cand->Function->isDeleted() ||
4316 Cand->Function->hasAttr<UnavailableAttr>())) {
John McCalla1d7d622010-01-08 00:58:21 +00004317 S.Diag(Cand->Function->getLocation(), diag::note_ovl_candidate_deleted)
4318 << Cand->Function->isDeleted();
4319 return;
John McCall81201622010-01-08 04:41:39 +00004320 }
4321
4322 if (FunctionTemplateDecl *FunTmpl
John McCalla1d7d622010-01-08 00:58:21 +00004323 = Cand->Function->getPrimaryTemplate()) {
4324 // Function template specialization
4325 // FIXME: Give a better reason!
4326 S.Diag(Cand->Function->getLocation(), diag::note_ovl_template_candidate)
4327 << S.getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4328 *Cand->Function->getTemplateSpecializationArgs());
4329 return;
4330 }
4331
4332 // Normal function
4333 bool errReported = false;
4334 if (!Cand->Viable && Cand->Conversions.size() > 0) {
4335 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4336 const ImplicitConversionSequence &Conversion =
4337 Cand->Conversions[i];
4338 if ((Conversion.ConversionKind !=
4339 ImplicitConversionSequence::BadConversion) ||
4340 Conversion.ConversionFunctionSet.size() == 0)
4341 continue;
4342 S.Diag(Cand->Function->getLocation(),
4343 diag::note_ovl_candidate_not_viable) << (i+1);
4344 errReported = true;
4345 for (int j = Conversion.ConversionFunctionSet.size()-1;
4346 j >= 0; j--) {
4347 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4348 S.NoteOverloadCandidate(Func);
4349 }
4350 }
4351 }
4352
4353 if (!errReported)
4354 S.NoteOverloadCandidate(Cand->Function);
4355}
4356
4357void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4358 // Desugar the type of the surrogate down to a function type,
4359 // retaining as many typedefs as possible while still showing
4360 // the function type (and, therefore, its parameter types).
4361 QualType FnType = Cand->Surrogate->getConversionType();
4362 bool isLValueReference = false;
4363 bool isRValueReference = false;
4364 bool isPointer = false;
4365 if (const LValueReferenceType *FnTypeRef =
4366 FnType->getAs<LValueReferenceType>()) {
4367 FnType = FnTypeRef->getPointeeType();
4368 isLValueReference = true;
4369 } else if (const RValueReferenceType *FnTypeRef =
4370 FnType->getAs<RValueReferenceType>()) {
4371 FnType = FnTypeRef->getPointeeType();
4372 isRValueReference = true;
4373 }
4374 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4375 FnType = FnTypePtr->getPointeeType();
4376 isPointer = true;
4377 }
4378 // Desugar down to a function type.
4379 FnType = QualType(FnType->getAs<FunctionType>(), 0);
4380 // Reconstruct the pointer/reference as appropriate.
4381 if (isPointer) FnType = S.Context.getPointerType(FnType);
4382 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
4383 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
4384
4385 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
4386 << FnType;
4387}
4388
4389void NoteBuiltinOperatorCandidate(Sema &S,
4390 const char *Opc,
4391 SourceLocation OpLoc,
4392 OverloadCandidate *Cand) {
4393 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
4394 std::string TypeStr("operator");
4395 TypeStr += Opc;
4396 TypeStr += "(";
4397 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4398 if (Cand->Conversions.size() == 1) {
4399 TypeStr += ")";
4400 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
4401 } else {
4402 TypeStr += ", ";
4403 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4404 TypeStr += ")";
4405 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
4406 }
4407}
4408
4409void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
4410 OverloadCandidate *Cand) {
4411 unsigned NoOperands = Cand->Conversions.size();
4412 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4413 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4414 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4415 ICS.ConversionFunctionSet.empty())
4416 continue;
4417 if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4418 Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4419 QualType FromTy =
4420 QualType(static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4421 S.Diag(OpLoc, diag::note_ambiguous_type_conversion)
4422 << FromTy << Func->getConversionType();
4423 }
4424 for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4425 FunctionDecl *Func =
4426 Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4427 S.NoteOverloadCandidate(Func);
4428 }
4429 }
4430}
4431
John McCall81201622010-01-08 04:41:39 +00004432struct CompareOverloadCandidates {
4433 SourceManager &SM;
4434 CompareOverloadCandidates(SourceManager &SM) : SM(SM) {}
4435
4436 bool operator()(const OverloadCandidate *L,
4437 const OverloadCandidate *R) {
4438 // Order first by viability.
4439 if (L->Viable != R->Viable)
4440 return L->Viable;
4441
4442 // Put declared functions first.
4443 if (L->Function) {
4444 if (!R->Function) return true;
4445 return SM.isBeforeInTranslationUnit(L->Function->getLocation(),
4446 R->Function->getLocation());
4447 } else if (R->Function) return false;
4448
4449 // Then surrogates.
4450 if (L->IsSurrogate) {
4451 if (!R->IsSurrogate) return true;
4452 return SM.isBeforeInTranslationUnit(L->Surrogate->getLocation(),
4453 R->Surrogate->getLocation());
4454 } else if (R->IsSurrogate) return false;
4455
4456 // And builtins just come in a jumble.
4457 return false;
4458 }
4459};
4460
John McCalla1d7d622010-01-08 00:58:21 +00004461} // end anonymous namespace
4462
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004463/// PrintOverloadCandidates - When overload resolution fails, prints
4464/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00004465/// set.
Mike Stump1eb44332009-09-09 15:08:12 +00004466void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004467Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall81201622010-01-08 04:41:39 +00004468 OverloadCandidateDisplayKind OCD,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004469 const char *Opc,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00004470 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00004471 // Sort the candidates by viability and position. Sorting directly would
4472 // be prohibitive, so we make a set of pointers and sort those.
4473 llvm::SmallVector<OverloadCandidate*, 32> Cands;
4474 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
4475 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4476 LastCand = CandidateSet.end();
4477 Cand != LastCand; ++Cand)
4478 if (Cand->Viable || OCD == OCD_AllCandidates)
4479 Cands.push_back(Cand);
4480 std::sort(Cands.begin(), Cands.end(), CompareOverloadCandidates(SourceMgr));
4481
John McCalla1d7d622010-01-08 00:58:21 +00004482 bool ReportedNonViableOperator = false;
4483
John McCall81201622010-01-08 04:41:39 +00004484 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
4485 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
4486 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00004487
John McCalla1d7d622010-01-08 00:58:21 +00004488 if (Cand->Function)
4489 NoteFunctionCandidate(*this, Cand);
4490 else if (Cand->IsSurrogate)
4491 NoteSurrogateCandidate(*this, Cand);
4492
4493 // This a builtin candidate. We do not, in general, want to list
4494 // every possible builtin candidate.
4495
John McCall81201622010-01-08 04:41:39 +00004496 // If this is a viable builtin, print it.
4497 else if (Cand->Viable)
John McCalla1d7d622010-01-08 00:58:21 +00004498 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
4499
4500 // Otherwise, non-viability might be due to ambiguous user-defined
4501 // conversions. Report them exactly once.
John McCall81201622010-01-08 04:41:39 +00004502 else if (!ReportedNonViableOperator) {
John McCalla1d7d622010-01-08 00:58:21 +00004503 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
4504 ReportedNonViableOperator = true;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004505 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004506 }
4507}
4508
Douglas Gregor904eed32008-11-10 20:40:00 +00004509/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4510/// an overloaded function (C++ [over.over]), where @p From is an
4511/// expression with overloaded function type and @p ToType is the type
4512/// we're trying to resolve to. For example:
4513///
4514/// @code
4515/// int f(double);
4516/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00004517///
Douglas Gregor904eed32008-11-10 20:40:00 +00004518/// int (*pfd)(double) = f; // selects f(double)
4519/// @endcode
4520///
4521/// This routine returns the resulting FunctionDecl if it could be
4522/// resolved, and NULL otherwise. When @p Complain is true, this
4523/// routine will emit diagnostics if there is an error.
4524FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00004525Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004526 bool Complain) {
4527 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00004528 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00004529 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00004530 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004531 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00004532 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00004533 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00004534 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00004535 FunctionType = MemTypePtr->getPointeeType();
4536 IsMember = true;
4537 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004538
4539 // We only look at pointers or references to functions.
Douglas Gregor72e771f2009-07-09 17:16:51 +00004540 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor83314aa2009-07-08 20:55:45 +00004541 if (!FunctionType->isFunctionType())
Douglas Gregor904eed32008-11-10 20:40:00 +00004542 return 0;
4543
4544 // Find the actual overloaded function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00004545
Douglas Gregor904eed32008-11-10 20:40:00 +00004546 // C++ [over.over]p1:
4547 // [...] [Note: any redundant set of parentheses surrounding the
4548 // overloaded function name is ignored (5.1). ]
4549 Expr *OvlExpr = From->IgnoreParens();
4550
4551 // C++ [over.over]p1:
4552 // [...] The overloaded function name can be preceded by the &
4553 // operator.
4554 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4555 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4556 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4557 }
4558
Anders Carlsson70534852009-10-20 22:53:47 +00004559 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00004560 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCallba135432009-11-21 08:51:07 +00004561
4562 llvm::SmallVector<NamedDecl*,8> Fns;
Anders Carlsson70534852009-10-20 22:53:47 +00004563
John McCall129e2df2009-11-30 22:42:35 +00004564 // Look into the overloaded expression.
John McCallf7a1a742009-11-24 19:00:30 +00004565 if (UnresolvedLookupExpr *UL
John McCallba135432009-11-21 08:51:07 +00004566 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4567 Fns.append(UL->decls_begin(), UL->decls_end());
John McCallf7a1a742009-11-24 19:00:30 +00004568 if (UL->hasExplicitTemplateArgs()) {
4569 HasExplicitTemplateArgs = true;
4570 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4571 }
John McCall129e2df2009-11-30 22:42:35 +00004572 } else if (UnresolvedMemberExpr *ME
4573 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4574 Fns.append(ME->decls_begin(), ME->decls_end());
4575 if (ME->hasExplicitTemplateArgs()) {
4576 HasExplicitTemplateArgs = true;
John McCalld5532b62009-11-23 01:53:49 +00004577 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004578 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00004579 }
Mike Stump1eb44332009-09-09 15:08:12 +00004580
John McCallba135432009-11-21 08:51:07 +00004581 // If we didn't actually find anything, we're done.
4582 if (Fns.empty())
4583 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004584
Douglas Gregor904eed32008-11-10 20:40:00 +00004585 // Look through all of the overloaded functions, searching for one
4586 // whose type matches exactly.
Douglas Gregor00aeb522009-07-08 23:33:52 +00004587 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004588 bool FoundNonTemplateFunction = false;
John McCallba135432009-11-21 08:51:07 +00004589 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4590 E = Fns.end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00004591 // Look through any using declarations to find the underlying function.
4592 NamedDecl *Fn = (*I)->getUnderlyingDecl();
4593
Douglas Gregor904eed32008-11-10 20:40:00 +00004594 // C++ [over.over]p3:
4595 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00004596 // targets of type "pointer-to-function" or "reference-to-function."
4597 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00004598 // type "pointer-to-member-function."
4599 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00004600
Mike Stump1eb44332009-09-09 15:08:12 +00004601 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00004602 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004603 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00004604 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004605 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00004606 // static when converting to member pointer.
4607 if (Method->isStatic() == IsMember)
4608 continue;
4609 } else if (IsMember)
4610 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00004611
Douglas Gregor00aeb522009-07-08 23:33:52 +00004612 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004613 // If the name is a function template, template argument deduction is
4614 // done (14.8.2.2), and if the argument deduction succeeds, the
4615 // resulting template argument list is used to generate a single
4616 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00004617 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004618 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00004619 FunctionDecl *Specialization = 0;
4620 TemplateDeductionInfo Info(Context);
4621 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00004622 = DeduceTemplateArguments(FunctionTemplate,
4623 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
Douglas Gregor83314aa2009-07-08 20:55:45 +00004624 FunctionType, Specialization, Info)) {
4625 // FIXME: make a note of the failed deduction for diagnostics.
4626 (void)Result;
4627 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004628 // FIXME: If the match isn't exact, shouldn't we just drop this as
4629 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00004630 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00004631 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00004632 Matches.insert(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00004633 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor83314aa2009-07-08 20:55:45 +00004634 }
John McCallba135432009-11-21 08:51:07 +00004635
4636 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00004637 }
Mike Stump1eb44332009-09-09 15:08:12 +00004638
Chandler Carruthbd647292009-12-29 06:17:27 +00004639 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00004640 // Skip non-static functions when converting to pointer, and static
4641 // when converting to member pointer.
4642 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00004643 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00004644
4645 // If we have explicit template arguments, skip non-templates.
4646 if (HasExplicitTemplateArgs)
4647 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004648 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00004649 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00004650
Chandler Carruthbd647292009-12-29 06:17:27 +00004651 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00004652 QualType ResultTy;
4653 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
4654 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
4655 ResultTy)) {
John McCallba135432009-11-21 08:51:07 +00004656 Matches.insert(cast<FunctionDecl>(FunDecl->getCanonicalDecl()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00004657 FoundNonTemplateFunction = true;
4658 }
Mike Stump1eb44332009-09-09 15:08:12 +00004659 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004660 }
4661
Douglas Gregor00aeb522009-07-08 23:33:52 +00004662 // If there were 0 or 1 matches, we're done.
4663 if (Matches.empty())
4664 return 0;
Sebastian Redl07ab2022009-10-17 21:12:09 +00004665 else if (Matches.size() == 1) {
4666 FunctionDecl *Result = *Matches.begin();
4667 MarkDeclarationReferenced(From->getLocStart(), Result);
4668 return Result;
4669 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00004670
4671 // C++ [over.over]p4:
4672 // If more than one function is selected, [...]
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004673 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregor312a2022009-09-26 03:56:17 +00004674 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004675 // [...] and any given function template specialization F1 is
4676 // eliminated if the set contains a second function template
4677 // specialization whose function template is more specialized
4678 // than the function template of F1 according to the partial
4679 // ordering rules of 14.5.5.2.
4680
4681 // The algorithm specified above is quadratic. We instead use a
4682 // two-pass algorithm (similar to the one used to identify the
4683 // best viable function in an overload set) that identifies the
4684 // best function template (if it exists).
Sebastian Redl07ab2022009-10-17 21:12:09 +00004685 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregor312a2022009-09-26 03:56:17 +00004686 Matches.end());
Sebastian Redl07ab2022009-10-17 21:12:09 +00004687 FunctionDecl *Result =
4688 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4689 TPOC_Other, From->getLocStart(),
4690 PDiag(),
4691 PDiag(diag::err_addr_ovl_ambiguous)
4692 << TemplateMatches[0]->getDeclName(),
John McCallb1622a12010-01-06 09:43:14 +00004693 PDiag(diag::note_ovl_template_candidate));
Sebastian Redl07ab2022009-10-17 21:12:09 +00004694 MarkDeclarationReferenced(From->getLocStart(), Result);
4695 return Result;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004696 }
Mike Stump1eb44332009-09-09 15:08:12 +00004697
Douglas Gregor312a2022009-09-26 03:56:17 +00004698 // [...] any function template specializations in the set are
4699 // eliminated if the set also contains a non-template function, [...]
4700 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4701 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4702 if ((*M)->getPrimaryTemplate() == 0)
4703 RemainingMatches.push_back(*M);
4704
Mike Stump1eb44332009-09-09 15:08:12 +00004705 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00004706 // selected function.
Sebastian Redl07ab2022009-10-17 21:12:09 +00004707 if (RemainingMatches.size() == 1) {
4708 FunctionDecl *Result = RemainingMatches.front();
4709 MarkDeclarationReferenced(From->getLocStart(), Result);
4710 return Result;
4711 }
Mike Stump1eb44332009-09-09 15:08:12 +00004712
Douglas Gregor00aeb522009-07-08 23:33:52 +00004713 // FIXME: We should probably return the same thing that BestViableFunction
4714 // returns (even if we issue the diagnostics here).
4715 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4716 << RemainingMatches[0]->getDeclName();
4717 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
John McCallb1622a12010-01-06 09:43:14 +00004718 NoteOverloadCandidate(RemainingMatches[I]);
Douglas Gregor904eed32008-11-10 20:40:00 +00004719 return 0;
4720}
4721
Douglas Gregor4b52e252009-12-21 23:17:24 +00004722/// \brief Given an expression that refers to an overloaded function, try to
4723/// resolve that overloaded function expression down to a single function.
4724///
4725/// This routine can only resolve template-ids that refer to a single function
4726/// template, where that template-id refers to a single template whose template
4727/// arguments are either provided by the template-id or have defaults,
4728/// as described in C++0x [temp.arg.explicit]p3.
4729FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
4730 // C++ [over.over]p1:
4731 // [...] [Note: any redundant set of parentheses surrounding the
4732 // overloaded function name is ignored (5.1). ]
4733 Expr *OvlExpr = From->IgnoreParens();
4734
4735 // C++ [over.over]p1:
4736 // [...] The overloaded function name can be preceded by the &
4737 // operator.
4738 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4739 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4740 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4741 }
4742
4743 bool HasExplicitTemplateArgs = false;
4744 TemplateArgumentListInfo ExplicitTemplateArgs;
4745
4746 llvm::SmallVector<NamedDecl*,8> Fns;
4747
4748 // Look into the overloaded expression.
4749 if (UnresolvedLookupExpr *UL
4750 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4751 Fns.append(UL->decls_begin(), UL->decls_end());
4752 if (UL->hasExplicitTemplateArgs()) {
4753 HasExplicitTemplateArgs = true;
4754 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4755 }
4756 } else if (UnresolvedMemberExpr *ME
4757 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4758 Fns.append(ME->decls_begin(), ME->decls_end());
4759 if (ME->hasExplicitTemplateArgs()) {
4760 HasExplicitTemplateArgs = true;
4761 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4762 }
4763 }
4764
4765 // If we didn't actually find any template-ids, we're done.
4766 if (Fns.empty() || !HasExplicitTemplateArgs)
4767 return 0;
4768
4769 // Look through all of the overloaded functions, searching for one
4770 // whose type matches exactly.
4771 FunctionDecl *Matched = 0;
4772 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4773 E = Fns.end(); I != E; ++I) {
4774 // C++0x [temp.arg.explicit]p3:
4775 // [...] In contexts where deduction is done and fails, or in contexts
4776 // where deduction is not done, if a template argument list is
4777 // specified and it, along with any default template arguments,
4778 // identifies a single function template specialization, then the
4779 // template-id is an lvalue for the function template specialization.
4780 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
4781
4782 // C++ [over.over]p2:
4783 // If the name is a function template, template argument deduction is
4784 // done (14.8.2.2), and if the argument deduction succeeds, the
4785 // resulting template argument list is used to generate a single
4786 // function template specialization, which is added to the set of
4787 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00004788 FunctionDecl *Specialization = 0;
4789 TemplateDeductionInfo Info(Context);
4790 if (TemplateDeductionResult Result
4791 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
4792 Specialization, Info)) {
4793 // FIXME: make a note of the failed deduction for diagnostics.
4794 (void)Result;
4795 continue;
4796 }
4797
4798 // Multiple matches; we can't resolve to a single declaration.
4799 if (Matched)
4800 return 0;
4801
4802 Matched = Specialization;
4803 }
4804
4805 return Matched;
4806}
4807
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004808/// \brief Add a single candidate to the overload set.
4809static void AddOverloadedCallCandidate(Sema &S,
John McCallba135432009-11-21 08:51:07 +00004810 NamedDecl *Callee,
John McCalld5532b62009-11-23 01:53:49 +00004811 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004812 Expr **Args, unsigned NumArgs,
4813 OverloadCandidateSet &CandidateSet,
4814 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00004815 if (isa<UsingShadowDecl>(Callee))
4816 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
4817
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004818 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00004819 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004820 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4821 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004822 return;
John McCallba135432009-11-21 08:51:07 +00004823 }
4824
4825 if (FunctionTemplateDecl *FuncTemplate
4826 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00004827 S.AddTemplateOverloadCandidate(FuncTemplate, ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00004828 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00004829 return;
4830 }
4831
4832 assert(false && "unhandled case in overloaded call candidate");
4833
4834 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004835}
4836
4837/// \brief Add the overload candidates named by callee and/or found by argument
4838/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00004839void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004840 Expr **Args, unsigned NumArgs,
4841 OverloadCandidateSet &CandidateSet,
4842 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00004843
4844#ifndef NDEBUG
4845 // Verify that ArgumentDependentLookup is consistent with the rules
4846 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004847 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004848 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4849 // and let Y be the lookup set produced by argument dependent
4850 // lookup (defined as follows). If X contains
4851 //
4852 // -- a declaration of a class member, or
4853 //
4854 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00004855 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004856 //
4857 // -- a declaration that is neither a function or a function
4858 // template
4859 //
4860 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00004861
John McCall3b4294e2009-12-16 12:17:52 +00004862 if (ULE->requiresADL()) {
4863 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
4864 E = ULE->decls_end(); I != E; ++I) {
4865 assert(!(*I)->getDeclContext()->isRecord());
4866 assert(isa<UsingShadowDecl>(*I) ||
4867 !(*I)->getDeclContext()->isFunctionOrMethod());
4868 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00004869 }
4870 }
4871#endif
4872
John McCall3b4294e2009-12-16 12:17:52 +00004873 // It would be nice to avoid this copy.
4874 TemplateArgumentListInfo TABuffer;
4875 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
4876 if (ULE->hasExplicitTemplateArgs()) {
4877 ULE->copyTemplateArgumentsInto(TABuffer);
4878 ExplicitTemplateArgs = &TABuffer;
4879 }
4880
4881 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
4882 E = ULE->decls_end(); I != E; ++I)
John McCalld5532b62009-11-23 01:53:49 +00004883 AddOverloadedCallCandidate(*this, *I, ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00004884 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004885 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00004886
John McCall3b4294e2009-12-16 12:17:52 +00004887 if (ULE->requiresADL())
4888 AddArgumentDependentLookupCandidates(ULE->getName(), Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004889 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004890 CandidateSet,
4891 PartialOverloading);
4892}
John McCall578b69b2009-12-16 08:11:27 +00004893
John McCall3b4294e2009-12-16 12:17:52 +00004894static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
4895 Expr **Args, unsigned NumArgs) {
4896 Fn->Destroy(SemaRef.Context);
4897 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4898 Args[Arg]->Destroy(SemaRef.Context);
4899 return SemaRef.ExprError();
4900}
4901
John McCall578b69b2009-12-16 08:11:27 +00004902/// Attempts to recover from a call where no functions were found.
4903///
4904/// Returns true if new candidates were found.
John McCall3b4294e2009-12-16 12:17:52 +00004905static Sema::OwningExprResult
4906BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn,
4907 UnresolvedLookupExpr *ULE,
4908 SourceLocation LParenLoc,
4909 Expr **Args, unsigned NumArgs,
4910 SourceLocation *CommaLocs,
4911 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00004912
4913 CXXScopeSpec SS;
4914 if (ULE->getQualifier()) {
4915 SS.setScopeRep(ULE->getQualifier());
4916 SS.setRange(ULE->getQualifierRange());
4917 }
4918
John McCall3b4294e2009-12-16 12:17:52 +00004919 TemplateArgumentListInfo TABuffer;
4920 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
4921 if (ULE->hasExplicitTemplateArgs()) {
4922 ULE->copyTemplateArgumentsInto(TABuffer);
4923 ExplicitTemplateArgs = &TABuffer;
4924 }
4925
John McCall578b69b2009-12-16 08:11:27 +00004926 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
4927 Sema::LookupOrdinaryName);
Douglas Gregorbb092ba2009-12-31 05:20:13 +00004928 if (SemaRef.DiagnoseEmptyLookup(/*Scope=*/0, SS, R))
John McCall3b4294e2009-12-16 12:17:52 +00004929 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCall578b69b2009-12-16 08:11:27 +00004930
John McCall3b4294e2009-12-16 12:17:52 +00004931 assert(!R.empty() && "lookup results empty despite recovery");
4932
4933 // Build an implicit member call if appropriate. Just drop the
4934 // casts and such from the call, we don't really care.
4935 Sema::OwningExprResult NewFn = SemaRef.ExprError();
4936 if ((*R.begin())->isCXXClassMember())
4937 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
4938 else if (ExplicitTemplateArgs)
4939 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
4940 else
4941 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
4942
4943 if (NewFn.isInvalid())
4944 return Destroy(SemaRef, Fn, Args, NumArgs);
4945
4946 Fn->Destroy(SemaRef.Context);
4947
4948 // This shouldn't cause an infinite loop because we're giving it
4949 // an expression with non-empty lookup results, which should never
4950 // end up here.
4951 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
4952 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
4953 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00004954}
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004955
Douglas Gregorf6b89692008-11-26 05:54:23 +00004956/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00004957/// (which eventually refers to the declaration Func) and the call
4958/// arguments Args/NumArgs, attempt to resolve the function call down
4959/// to a specific function. If overload resolution succeeds, returns
4960/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00004961/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00004962/// arguments and Fn, and returns NULL.
John McCall3b4294e2009-12-16 12:17:52 +00004963Sema::OwningExprResult
4964Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE,
4965 SourceLocation LParenLoc,
4966 Expr **Args, unsigned NumArgs,
4967 SourceLocation *CommaLocs,
4968 SourceLocation RParenLoc) {
4969#ifndef NDEBUG
4970 if (ULE->requiresADL()) {
4971 // To do ADL, we must have found an unqualified name.
4972 assert(!ULE->getQualifier() && "qualified name with ADL");
4973
4974 // We don't perform ADL for implicit declarations of builtins.
4975 // Verify that this was correctly set up.
4976 FunctionDecl *F;
4977 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
4978 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
4979 F->getBuiltinID() && F->isImplicit())
4980 assert(0 && "performing ADL for builtin");
4981
4982 // We don't perform ADL in C.
4983 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
4984 }
4985#endif
4986
Douglas Gregorf6b89692008-11-26 05:54:23 +00004987 OverloadCandidateSet CandidateSet;
Douglas Gregor17330012009-02-04 15:01:18 +00004988
John McCall3b4294e2009-12-16 12:17:52 +00004989 // Add the functions denoted by the callee to the set of candidate
4990 // functions, including those from argument-dependent lookup.
4991 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00004992
4993 // If we found nothing, try to recover.
4994 // AddRecoveryCallCandidates diagnoses the error itself, so we just
4995 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00004996 if (CandidateSet.empty())
4997 return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs,
4998 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00004999
Douglas Gregorf6b89692008-11-26 05:54:23 +00005000 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005001 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00005002 case OR_Success: {
5003 FunctionDecl *FDecl = Best->Function;
5004 Fn = FixOverloadedFunctionReference(Fn, FDecl);
5005 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5006 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00005007
5008 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00005009 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00005010 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00005011 << ULE->getName() << Fn->getSourceRange();
John McCall81201622010-01-08 04:41:39 +00005012 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Douglas Gregorf6b89692008-11-26 05:54:23 +00005013 break;
5014
5015 case OR_Ambiguous:
5016 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00005017 << ULE->getName() << Fn->getSourceRange();
John McCall81201622010-01-08 04:41:39 +00005018 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates);
Douglas Gregorf6b89692008-11-26 05:54:23 +00005019 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005020
5021 case OR_Deleted:
5022 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5023 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00005024 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005025 << Fn->getSourceRange();
John McCall81201622010-01-08 04:41:39 +00005026 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005027 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00005028 }
5029
5030 // Overload resolution failed. Destroy all of the subexpressions and
5031 // return NULL.
5032 Fn->Destroy(Context);
5033 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5034 Args[Arg]->Destroy(Context);
John McCall3b4294e2009-12-16 12:17:52 +00005035 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00005036}
5037
John McCall7453ed42009-11-22 00:44:51 +00005038static bool IsOverloaded(const Sema::FunctionSet &Functions) {
5039 return Functions.size() > 1 ||
5040 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5041}
5042
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005043/// \brief Create a unary operation that may resolve to an overloaded
5044/// operator.
5045///
5046/// \param OpLoc The location of the operator itself (e.g., '*').
5047///
5048/// \param OpcIn The UnaryOperator::Opcode that describes this
5049/// operator.
5050///
5051/// \param Functions The set of non-member functions that will be
5052/// considered by overload resolution. The caller needs to build this
5053/// set based on the context using, e.g.,
5054/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5055/// set should not contain any member functions; those will be added
5056/// by CreateOverloadedUnaryOp().
5057///
5058/// \param input The input argument.
5059Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
5060 unsigned OpcIn,
5061 FunctionSet &Functions,
Mike Stump1eb44332009-09-09 15:08:12 +00005062 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005063 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5064 Expr *Input = (Expr *)input.get();
5065
5066 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5067 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5068 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5069
5070 Expr *Args[2] = { Input, 0 };
5071 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00005072
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005073 // For post-increment and post-decrement, add the implicit '0' as
5074 // the second argument, so that we know this is a post-increment or
5075 // post-decrement.
5076 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5077 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00005078 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005079 SourceLocation());
5080 NumArgs = 2;
5081 }
5082
5083 if (Input->isTypeDependent()) {
John McCallba135432009-11-21 08:51:07 +00005084 UnresolvedLookupExpr *Fn
John McCallf7a1a742009-11-24 19:00:30 +00005085 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5086 0, SourceRange(), OpName, OpLoc,
John McCall7453ed42009-11-22 00:44:51 +00005087 /*ADL*/ true, IsOverloaded(Functions));
Mike Stump1eb44332009-09-09 15:08:12 +00005088 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005089 FuncEnd = Functions.end();
5090 Func != FuncEnd; ++Func)
John McCallba135432009-11-21 08:51:07 +00005091 Fn->addDecl(*Func);
Mike Stump1eb44332009-09-09 15:08:12 +00005092
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005093 input.release();
5094 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5095 &Args[0], NumArgs,
5096 Context.DependentTy,
5097 OpLoc));
5098 }
5099
5100 // Build an empty overload set.
5101 OverloadCandidateSet CandidateSet;
5102
5103 // Add the candidates from the given function set.
5104 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
5105
5106 // Add operator candidates that are member functions.
5107 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5108
5109 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00005110 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005111
5112 // Perform overload resolution.
5113 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005114 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005115 case OR_Success: {
5116 // We found a built-in operator or an overloaded operator.
5117 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00005118
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005119 if (FnDecl) {
5120 // We matched an overloaded operator. Build a call to that
5121 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00005122
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005123 // Convert the arguments.
5124 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
5125 if (PerformObjectArgumentInitialization(Input, Method))
5126 return ExprError();
5127 } else {
5128 // Convert the arguments.
Douglas Gregore1a5c172009-12-23 17:40:29 +00005129 OwningExprResult InputInit
5130 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005131 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00005132 SourceLocation(),
5133 move(input));
5134 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005135 return ExprError();
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005136
Douglas Gregore1a5c172009-12-23 17:40:29 +00005137 input = move(InputInit);
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005138 Input = (Expr *)input.get();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005139 }
5140
5141 // Determine the result type
Anders Carlsson26a2a072009-10-13 21:19:37 +00005142 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00005143
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005144 // Build the actual expression node.
5145 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5146 SourceLocation());
5147 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00005148
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005149 input.release();
Eli Friedman4c3b8962009-11-18 03:58:17 +00005150 Args[0] = Input;
Anders Carlsson26a2a072009-10-13 21:19:37 +00005151 ExprOwningPtr<CallExpr> TheCall(this,
5152 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman4c3b8962009-11-18 03:58:17 +00005153 Args, NumArgs, ResultTy, OpLoc));
Anders Carlsson26a2a072009-10-13 21:19:37 +00005154
5155 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5156 FnDecl))
5157 return ExprError();
5158
5159 return MaybeBindToTemporary(TheCall.release());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005160 } else {
5161 // We matched a built-in operator. Convert the arguments, then
5162 // break out so that we will build the appropriate built-in
5163 // operator node.
5164 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005165 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005166 return ExprError();
5167
5168 break;
5169 }
5170 }
5171
5172 case OR_No_Viable_Function:
5173 // No viable function; fall through to handling this as a
5174 // built-in operator, which will produce an error message for us.
5175 break;
5176
5177 case OR_Ambiguous:
5178 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5179 << UnaryOperator::getOpcodeStr(Opc)
5180 << Input->getSourceRange();
John McCall81201622010-01-08 04:41:39 +00005181 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005182 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005183 return ExprError();
5184
5185 case OR_Deleted:
5186 Diag(OpLoc, diag::err_ovl_deleted_oper)
5187 << Best->Function->isDeleted()
5188 << UnaryOperator::getOpcodeStr(Opc)
5189 << Input->getSourceRange();
John McCall81201622010-01-08 04:41:39 +00005190 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005191 return ExprError();
5192 }
5193
5194 // Either we found no viable overloaded operator or we matched a
5195 // built-in operator. In either case, fall through to trying to
5196 // build a built-in operation.
5197 input.release();
5198 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5199}
5200
Douglas Gregor063daf62009-03-13 18:40:31 +00005201/// \brief Create a binary operation that may resolve to an overloaded
5202/// operator.
5203///
5204/// \param OpLoc The location of the operator itself (e.g., '+').
5205///
5206/// \param OpcIn The BinaryOperator::Opcode that describes this
5207/// operator.
5208///
5209/// \param Functions The set of non-member functions that will be
5210/// considered by overload resolution. The caller needs to build this
5211/// set based on the context using, e.g.,
5212/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5213/// set should not contain any member functions; those will be added
5214/// by CreateOverloadedBinOp().
5215///
5216/// \param LHS Left-hand argument.
5217/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00005218Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00005219Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005220 unsigned OpcIn,
Douglas Gregor063daf62009-03-13 18:40:31 +00005221 FunctionSet &Functions,
5222 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00005223 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005224 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00005225
5226 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5227 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5228 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5229
5230 // If either side is type-dependent, create an appropriate dependent
5231 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005232 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005233 if (Functions.empty()) {
5234 // If there are no functions to store, just build a dependent
5235 // BinaryOperator or CompoundAssignment.
5236 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5237 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5238 Context.DependentTy, OpLoc));
5239
5240 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5241 Context.DependentTy,
5242 Context.DependentTy,
5243 Context.DependentTy,
5244 OpLoc));
5245 }
5246
John McCallba135432009-11-21 08:51:07 +00005247 UnresolvedLookupExpr *Fn
John McCallf7a1a742009-11-24 19:00:30 +00005248 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5249 0, SourceRange(), OpName, OpLoc,
John McCall7453ed42009-11-22 00:44:51 +00005250 /* ADL */ true, IsOverloaded(Functions));
John McCallba135432009-11-21 08:51:07 +00005251
Mike Stump1eb44332009-09-09 15:08:12 +00005252 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor063daf62009-03-13 18:40:31 +00005253 FuncEnd = Functions.end();
5254 Func != FuncEnd; ++Func)
John McCallba135432009-11-21 08:51:07 +00005255 Fn->addDecl(*Func);
Mike Stump1eb44332009-09-09 15:08:12 +00005256
Douglas Gregor063daf62009-03-13 18:40:31 +00005257 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00005258 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00005259 Context.DependentTy,
5260 OpLoc));
5261 }
5262
5263 // If this is the .* operator, which is not overloadable, just
5264 // create a built-in binary operator.
5265 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005266 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005267
Sebastian Redl275c2b42009-11-18 23:10:33 +00005268 // If this is the assignment operator, we only perform overload resolution
5269 // if the left-hand side is a class or enumeration type. This is actually
5270 // a hack. The standard requires that we do overload resolution between the
5271 // various built-in candidates, but as DR507 points out, this can lead to
5272 // problems. So we do it this way, which pretty much follows what GCC does.
5273 // Note that we go the traditional code path for compound assignment forms.
5274 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005275 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005276
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005277 // Build an empty overload set.
5278 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00005279
5280 // Add the candidates from the given function set.
5281 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
5282
5283 // Add operator candidates that are member functions.
5284 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5285
5286 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00005287 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00005288
5289 // Perform overload resolution.
5290 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005291 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005292 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00005293 // We found a built-in operator or an overloaded operator.
5294 FunctionDecl *FnDecl = Best->Function;
5295
5296 if (FnDecl) {
5297 // We matched an overloaded operator. Build a call to that
5298 // operator.
5299
5300 // Convert the arguments.
5301 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005302 OwningExprResult Arg1
5303 = PerformCopyInitialization(
5304 InitializedEntity::InitializeParameter(
5305 FnDecl->getParamDecl(0)),
5306 SourceLocation(),
5307 Owned(Args[1]));
5308 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00005309 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005310
5311 if (PerformObjectArgumentInitialization(Args[0], Method))
5312 return ExprError();
5313
5314 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00005315 } else {
5316 // Convert the arguments.
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005317 OwningExprResult Arg0
5318 = PerformCopyInitialization(
5319 InitializedEntity::InitializeParameter(
5320 FnDecl->getParamDecl(0)),
5321 SourceLocation(),
5322 Owned(Args[0]));
5323 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00005324 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005325
5326 OwningExprResult Arg1
5327 = PerformCopyInitialization(
5328 InitializedEntity::InitializeParameter(
5329 FnDecl->getParamDecl(1)),
5330 SourceLocation(),
5331 Owned(Args[1]));
5332 if (Arg1.isInvalid())
5333 return ExprError();
5334 Args[0] = LHS = Arg0.takeAs<Expr>();
5335 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00005336 }
5337
5338 // Determine the result type
5339 QualType ResultTy
John McCall183700f2009-09-21 23:43:11 +00005340 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor063daf62009-03-13 18:40:31 +00005341 ResultTy = ResultTy.getNonReferenceType();
5342
5343 // Build the actual expression node.
5344 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00005345 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00005346 UsualUnaryConversions(FnExpr);
5347
Anders Carlsson15ea3782009-10-13 22:43:21 +00005348 ExprOwningPtr<CXXOperatorCallExpr>
5349 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5350 Args, 2, ResultTy,
5351 OpLoc));
5352
5353 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5354 FnDecl))
5355 return ExprError();
5356
5357 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor063daf62009-03-13 18:40:31 +00005358 } else {
5359 // We matched a built-in operator. Convert the arguments, then
5360 // break out so that we will build the appropriate built-in
5361 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005362 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005363 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005364 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00005365 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00005366 return ExprError();
5367
5368 break;
5369 }
5370 }
5371
Douglas Gregor33074752009-09-30 21:46:01 +00005372 case OR_No_Viable_Function: {
5373 // C++ [over.match.oper]p9:
5374 // If the operator is the operator , [...] and there are no
5375 // viable functions, then the operator is assumed to be the
5376 // built-in operator and interpreted according to clause 5.
5377 if (Opc == BinaryOperator::Comma)
5378 break;
5379
Sebastian Redl8593c782009-05-21 11:50:50 +00005380 // For class as left operand for assignment or compound assigment operator
5381 // do not fall through to handling in built-in, but report that no overloaded
5382 // assignment operator found
Douglas Gregor33074752009-09-30 21:46:01 +00005383 OwningExprResult Result = ExprError();
5384 if (Args[0]->getType()->isRecordType() &&
5385 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00005386 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5387 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005388 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00005389 } else {
5390 // No viable function; try to create a built-in operation, which will
5391 // produce an error. Then, show the non-viable candidates.
5392 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00005393 }
Douglas Gregor33074752009-09-30 21:46:01 +00005394 assert(Result.isInvalid() &&
5395 "C++ binary operator overloading is missing candidates!");
5396 if (Result.isInvalid())
John McCall81201622010-01-08 04:41:39 +00005397 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005398 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00005399 return move(Result);
5400 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005401
5402 case OR_Ambiguous:
5403 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5404 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005405 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall81201622010-01-08 04:41:39 +00005406 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005407 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00005408 return ExprError();
5409
5410 case OR_Deleted:
5411 Diag(OpLoc, diag::err_ovl_deleted_oper)
5412 << Best->Function->isDeleted()
5413 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005414 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall81201622010-01-08 04:41:39 +00005415 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Douglas Gregor063daf62009-03-13 18:40:31 +00005416 return ExprError();
5417 }
5418
Douglas Gregor33074752009-09-30 21:46:01 +00005419 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005420 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005421}
5422
Sebastian Redlf322ed62009-10-29 20:17:01 +00005423Action::OwningExprResult
5424Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5425 SourceLocation RLoc,
5426 ExprArg Base, ExprArg Idx) {
5427 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5428 static_cast<Expr*>(Idx.get()) };
5429 DeclarationName OpName =
5430 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5431
5432 // If either side is type-dependent, create an appropriate dependent
5433 // expression.
5434 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5435
John McCallba135432009-11-21 08:51:07 +00005436 UnresolvedLookupExpr *Fn
John McCallf7a1a742009-11-24 19:00:30 +00005437 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5438 0, SourceRange(), OpName, LLoc,
John McCall7453ed42009-11-22 00:44:51 +00005439 /*ADL*/ true, /*Overloaded*/ false);
John McCallf7a1a742009-11-24 19:00:30 +00005440 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00005441
5442 Base.release();
5443 Idx.release();
5444 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5445 Args, 2,
5446 Context.DependentTy,
5447 RLoc));
5448 }
5449
5450 // Build an empty overload set.
5451 OverloadCandidateSet CandidateSet;
5452
5453 // Subscript can only be overloaded as a member function.
5454
5455 // Add operator candidates that are member functions.
5456 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5457
5458 // Add builtin operator candidates.
5459 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5460
5461 // Perform overload resolution.
5462 OverloadCandidateSet::iterator Best;
5463 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5464 case OR_Success: {
5465 // We found a built-in operator or an overloaded operator.
5466 FunctionDecl *FnDecl = Best->Function;
5467
5468 if (FnDecl) {
5469 // We matched an overloaded operator. Build a call to that
5470 // operator.
5471
5472 // Convert the arguments.
5473 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5474 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5475 PerformCopyInitialization(Args[1],
5476 FnDecl->getParamDecl(0)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +00005477 AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00005478 return ExprError();
5479
5480 // Determine the result type
5481 QualType ResultTy
5482 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5483 ResultTy = ResultTy.getNonReferenceType();
5484
5485 // Build the actual expression node.
5486 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5487 LLoc);
5488 UsualUnaryConversions(FnExpr);
5489
5490 Base.release();
5491 Idx.release();
5492 ExprOwningPtr<CXXOperatorCallExpr>
5493 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5494 FnExpr, Args, 2,
5495 ResultTy, RLoc));
5496
5497 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5498 FnDecl))
5499 return ExprError();
5500
5501 return MaybeBindToTemporary(TheCall.release());
5502 } else {
5503 // We matched a built-in operator. Convert the arguments, then
5504 // break out so that we will build the appropriate built-in
5505 // operator node.
5506 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005507 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00005508 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00005509 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00005510 return ExprError();
5511
5512 break;
5513 }
5514 }
5515
5516 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00005517 if (CandidateSet.empty())
5518 Diag(LLoc, diag::err_ovl_no_oper)
5519 << Args[0]->getType() << /*subscript*/ 0
5520 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5521 else
5522 Diag(LLoc, diag::err_ovl_no_viable_subscript)
5523 << Args[0]->getType()
5524 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall81201622010-01-08 04:41:39 +00005525 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates,
John McCall1eb3e102010-01-07 02:04:15 +00005526 "[]", LLoc);
5527 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00005528 }
5529
5530 case OR_Ambiguous:
5531 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5532 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall81201622010-01-08 04:41:39 +00005533 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates,
Sebastian Redlf322ed62009-10-29 20:17:01 +00005534 "[]", LLoc);
5535 return ExprError();
5536
5537 case OR_Deleted:
5538 Diag(LLoc, diag::err_ovl_deleted_oper)
5539 << Best->Function->isDeleted() << "[]"
5540 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall81201622010-01-08 04:41:39 +00005541 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates,
5542 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00005543 return ExprError();
5544 }
5545
5546 // We matched a built-in operator; build it.
5547 Base.release();
5548 Idx.release();
5549 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5550 Owned(Args[1]), RLoc);
5551}
5552
Douglas Gregor88a35142008-12-22 05:46:06 +00005553/// BuildCallToMemberFunction - Build a call to a member
5554/// function. MemExpr is the expression that refers to the member
5555/// function (and includes the object parameter), Args/NumArgs are the
5556/// arguments to the function call (not including the object
5557/// parameter). The caller needs to validate that the member
5558/// expression refers to a member function or an overloaded member
5559/// function.
John McCallaa81e162009-12-01 22:10:20 +00005560Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00005561Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5562 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00005563 unsigned NumArgs, SourceLocation *CommaLocs,
5564 SourceLocation RParenLoc) {
5565 // Dig out the member expression. This holds both the object
5566 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00005567 Expr *NakedMemExpr = MemExprE->IgnoreParens();
5568
John McCall129e2df2009-11-30 22:42:35 +00005569 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00005570 CXXMethodDecl *Method = 0;
John McCall129e2df2009-11-30 22:42:35 +00005571 if (isa<MemberExpr>(NakedMemExpr)) {
5572 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00005573 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5574 } else {
5575 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
John McCallaa81e162009-12-01 22:10:20 +00005576
John McCall701c89e2009-12-03 04:06:58 +00005577 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00005578
Douglas Gregor88a35142008-12-22 05:46:06 +00005579 // Add overload candidates
5580 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00005581
John McCallaa81e162009-12-01 22:10:20 +00005582 // FIXME: avoid copy.
5583 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5584 if (UnresExpr->hasExplicitTemplateArgs()) {
5585 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5586 TemplateArgs = &TemplateArgsBuffer;
5587 }
5588
John McCall129e2df2009-11-30 22:42:35 +00005589 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
5590 E = UnresExpr->decls_end(); I != E; ++I) {
5591
John McCall701c89e2009-12-03 04:06:58 +00005592 NamedDecl *Func = *I;
5593 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
5594 if (isa<UsingShadowDecl>(Func))
5595 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
5596
John McCall129e2df2009-11-30 22:42:35 +00005597 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005598 // If explicit template arguments were provided, we can't call a
5599 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00005600 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005601 continue;
5602
John McCall701c89e2009-12-03 04:06:58 +00005603 AddMethodCandidate(Method, ActingDC, ObjectType, Args, NumArgs,
5604 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00005605 } else {
John McCall129e2df2009-11-30 22:42:35 +00005606 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall701c89e2009-12-03 04:06:58 +00005607 ActingDC, TemplateArgs,
5608 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00005609 CandidateSet,
5610 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00005611 }
Douglas Gregordec06662009-08-21 18:42:58 +00005612 }
Mike Stump1eb44332009-09-09 15:08:12 +00005613
John McCall129e2df2009-11-30 22:42:35 +00005614 DeclarationName DeclName = UnresExpr->getMemberName();
5615
Douglas Gregor88a35142008-12-22 05:46:06 +00005616 OverloadCandidateSet::iterator Best;
John McCall129e2df2009-11-30 22:42:35 +00005617 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005618 case OR_Success:
5619 Method = cast<CXXMethodDecl>(Best->Function);
5620 break;
5621
5622 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00005623 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00005624 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00005625 << DeclName << MemExprE->getSourceRange();
John McCall81201622010-01-08 04:41:39 +00005626 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Douglas Gregor88a35142008-12-22 05:46:06 +00005627 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00005628 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00005629
5630 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00005631 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00005632 << DeclName << MemExprE->getSourceRange();
John McCall81201622010-01-08 04:41:39 +00005633 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Douglas Gregor88a35142008-12-22 05:46:06 +00005634 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00005635 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005636
5637 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00005638 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005639 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00005640 << DeclName << MemExprE->getSourceRange();
John McCall81201622010-01-08 04:41:39 +00005641 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005642 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00005643 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00005644 }
5645
Douglas Gregor699ee522009-11-20 19:42:02 +00005646 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCallaa81e162009-12-01 22:10:20 +00005647
John McCallaa81e162009-12-01 22:10:20 +00005648 // If overload resolution picked a static member, build a
5649 // non-member call based on that function.
5650 if (Method->isStatic()) {
5651 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
5652 Args, NumArgs, RParenLoc);
5653 }
5654
John McCall129e2df2009-11-30 22:42:35 +00005655 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00005656 }
5657
5658 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00005659 ExprOwningPtr<CXXMemberCallExpr>
John McCallaa81e162009-12-01 22:10:20 +00005660 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00005661 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00005662 Method->getResultType().getNonReferenceType(),
5663 RParenLoc));
5664
Anders Carlssoneed3e692009-10-10 00:06:20 +00005665 // Check for a valid return type.
5666 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5667 TheCall.get(), Method))
John McCallaa81e162009-12-01 22:10:20 +00005668 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00005669
Douglas Gregor88a35142008-12-22 05:46:06 +00005670 // Convert the object argument (for a non-static member function call).
John McCallaa81e162009-12-01 22:10:20 +00005671 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00005672 if (!Method->isStatic() &&
Douglas Gregor88a35142008-12-22 05:46:06 +00005673 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCallaa81e162009-12-01 22:10:20 +00005674 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00005675 MemExpr->setBase(ObjectArg);
5676
5677 // Convert the rest of the arguments
Douglas Gregor72564e72009-02-26 23:50:07 +00005678 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00005679 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00005680 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00005681 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00005682
Anders Carlssond406bf02009-08-16 01:56:34 +00005683 if (CheckFunctionCall(Method, TheCall.get()))
John McCallaa81e162009-12-01 22:10:20 +00005684 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00005685
John McCallaa81e162009-12-01 22:10:20 +00005686 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor88a35142008-12-22 05:46:06 +00005687}
5688
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005689/// BuildCallToObjectOfClassType - Build a call to an object of class
5690/// type (C++ [over.call.object]), which can end up invoking an
5691/// overloaded function call operator (@c operator()) or performing a
5692/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00005693Sema::ExprResult
5694Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00005695 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005696 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00005697 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005698 SourceLocation RParenLoc) {
5699 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00005700 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005701
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005702 // C++ [over.call.object]p1:
5703 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00005704 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005705 // candidate functions includes at least the function call
5706 // operators of T. The function call operators of T are obtained by
5707 // ordinary lookup of the name operator() in the context of
5708 // (E).operator().
5709 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00005710 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00005711
5712 if (RequireCompleteType(LParenLoc, Object->getType(),
5713 PartialDiagnostic(diag::err_incomplete_object_call)
5714 << Object->getSourceRange()))
5715 return true;
5716
John McCalla24dc2e2009-11-17 02:14:36 +00005717 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5718 LookupQualifiedName(R, Record->getDecl());
5719 R.suppressDiagnostics();
5720
Douglas Gregor593564b2009-11-15 07:48:03 +00005721 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00005722 Oper != OperEnd; ++Oper) {
John McCall701c89e2009-12-03 04:06:58 +00005723 AddMethodCandidate(*Oper, Object->getType(), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00005724 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00005725 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00005726
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005727 // C++ [over.call.object]p2:
5728 // In addition, for each conversion function declared in T of the
5729 // form
5730 //
5731 // operator conversion-type-id () cv-qualifier;
5732 //
5733 // where cv-qualifier is the same cv-qualification as, or a
5734 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00005735 // denotes the type "pointer to function of (P1,...,Pn) returning
5736 // R", or the type "reference to pointer to function of
5737 // (P1,...,Pn) returning R", or the type "reference to function
5738 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005739 // is also considered as a candidate function. Similarly,
5740 // surrogate call functions are added to the set of candidate
5741 // functions for each conversion function declared in an
5742 // accessible base class provided the function is not hidden
5743 // within T by another intervening declaration.
John McCallba135432009-11-21 08:51:07 +00005744 const UnresolvedSet *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00005745 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00005746 for (UnresolvedSet::iterator I = Conversions->begin(),
5747 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00005748 NamedDecl *D = *I;
5749 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5750 if (isa<UsingShadowDecl>(D))
5751 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5752
Douglas Gregor4a27d702009-10-21 06:18:39 +00005753 // Skip over templated conversion functions; they aren't
5754 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00005755 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00005756 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005757
John McCall701c89e2009-12-03 04:06:58 +00005758 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00005759
Douglas Gregor4a27d702009-10-21 06:18:39 +00005760 // Strip the reference type (if any) and then the pointer type (if
5761 // any) to get down to what might be a function type.
5762 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5763 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5764 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005765
Douglas Gregor4a27d702009-10-21 06:18:39 +00005766 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall701c89e2009-12-03 04:06:58 +00005767 AddSurrogateCandidate(Conv, ActingContext, Proto,
5768 Object->getType(), Args, NumArgs,
5769 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005770 }
Mike Stump1eb44332009-09-09 15:08:12 +00005771
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005772 // Perform overload resolution.
5773 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005774 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005775 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005776 // Overload resolution succeeded; we'll build the appropriate call
5777 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005778 break;
5779
5780 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00005781 if (CandidateSet.empty())
5782 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
5783 << Object->getType() << /*call*/ 1
5784 << Object->getSourceRange();
5785 else
5786 Diag(Object->getSourceRange().getBegin(),
5787 diag::err_ovl_no_viable_object_call)
5788 << Object->getType() << Object->getSourceRange();
John McCall81201622010-01-08 04:41:39 +00005789 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005790 break;
5791
5792 case OR_Ambiguous:
5793 Diag(Object->getSourceRange().getBegin(),
5794 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00005795 << Object->getType() << Object->getSourceRange();
John McCall81201622010-01-08 04:41:39 +00005796 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005797 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005798
5799 case OR_Deleted:
5800 Diag(Object->getSourceRange().getBegin(),
5801 diag::err_ovl_deleted_object_call)
5802 << Best->Function->isDeleted()
5803 << Object->getType() << Object->getSourceRange();
John McCall81201622010-01-08 04:41:39 +00005804 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005805 break;
Mike Stump1eb44332009-09-09 15:08:12 +00005806 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005807
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005808 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005809 // We had an error; delete all of the subexpressions and return
5810 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00005811 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005812 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00005813 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005814 return true;
5815 }
5816
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005817 if (Best->Function == 0) {
5818 // Since there is no function declaration, this is one of the
5819 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00005820 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005821 = cast<CXXConversionDecl>(
5822 Best->Conversions[0].UserDefined.ConversionFunction);
5823
5824 // We selected one of the surrogate functions that converts the
5825 // object parameter to a function pointer. Perform the conversion
5826 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00005827
5828 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00005829 // and then call it.
Eli Friedmanc8c771e2009-12-09 04:52:43 +00005830 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00005831
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00005832 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00005833 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5834 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005835 }
5836
5837 // We found an overloaded operator(). Build a CXXOperatorCallExpr
5838 // that calls this method, using Object for the implicit object
5839 // parameter and passing along the remaining arguments.
5840 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00005841 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005842
5843 unsigned NumArgsInProto = Proto->getNumArgs();
5844 unsigned NumArgsToCheck = NumArgs;
5845
5846 // Build the full argument list for the method call (the
5847 // implicit object parameter is placed at the beginning of the
5848 // list).
5849 Expr **MethodArgs;
5850 if (NumArgs < NumArgsInProto) {
5851 NumArgsToCheck = NumArgsInProto;
5852 MethodArgs = new Expr*[NumArgsInProto + 1];
5853 } else {
5854 MethodArgs = new Expr*[NumArgs + 1];
5855 }
5856 MethodArgs[0] = Object;
5857 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5858 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00005859
5860 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00005861 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005862 UsualUnaryConversions(NewFn);
5863
5864 // Once we've built TheCall, all of the expressions are properly
5865 // owned.
5866 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00005867 ExprOwningPtr<CXXOperatorCallExpr>
5868 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00005869 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005870 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005871 delete [] MethodArgs;
5872
Anders Carlsson07d68f12009-10-13 21:49:31 +00005873 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5874 Method))
5875 return true;
5876
Douglas Gregor518fda12009-01-13 05:10:00 +00005877 // We may have default arguments. If so, we need to allocate more
5878 // slots in the call for them.
5879 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00005880 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00005881 else if (NumArgs > NumArgsInProto)
5882 NumArgsToCheck = NumArgsInProto;
5883
Chris Lattner312531a2009-04-12 08:11:20 +00005884 bool IsError = false;
5885
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005886 // Initialize the implicit object parameter.
Chris Lattner312531a2009-04-12 08:11:20 +00005887 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005888 TheCall->setArg(0, Object);
5889
Chris Lattner312531a2009-04-12 08:11:20 +00005890
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005891 // Check the argument types.
5892 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005893 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00005894 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005895 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00005896
Douglas Gregor518fda12009-01-13 05:10:00 +00005897 // Pass the argument.
5898 QualType ProtoArgType = Proto->getArgType(i);
Douglas Gregor68647482009-12-16 03:45:30 +00005899 IsError |= PerformCopyInitialization(Arg, ProtoArgType, AA_Passing);
Douglas Gregor518fda12009-01-13 05:10:00 +00005900 } else {
Douglas Gregord47c47d2009-11-09 19:27:57 +00005901 OwningExprResult DefArg
5902 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
5903 if (DefArg.isInvalid()) {
5904 IsError = true;
5905 break;
5906 }
5907
5908 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00005909 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005910
5911 TheCall->setArg(i + 1, Arg);
5912 }
5913
5914 // If this is a variadic call, handle args passed through "...".
5915 if (Proto->isVariadic()) {
5916 // Promote the arguments (C99 6.5.2.2p7).
5917 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5918 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00005919 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005920 TheCall->setArg(i + 1, Arg);
5921 }
5922 }
5923
Chris Lattner312531a2009-04-12 08:11:20 +00005924 if (IsError) return true;
5925
Anders Carlssond406bf02009-08-16 01:56:34 +00005926 if (CheckFunctionCall(Method, TheCall.get()))
5927 return true;
5928
Anders Carlssona303f9e2009-08-16 03:53:54 +00005929 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005930}
5931
Douglas Gregor8ba10742008-11-20 16:27:02 +00005932/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00005933/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00005934/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005935Sema::OwningExprResult
5936Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5937 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00005938 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00005939
Douglas Gregor8ba10742008-11-20 16:27:02 +00005940 // C++ [over.ref]p1:
5941 //
5942 // [...] An expression x->m is interpreted as (x.operator->())->m
5943 // for a class object x of type T if T::operator->() exists and if
5944 // the operator is selected as the best match function by the
5945 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00005946 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5947 OverloadCandidateSet CandidateSet;
Ted Kremenek6217b802009-07-29 21:53:49 +00005948 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005949
Eli Friedmanf43fb722009-11-18 01:28:03 +00005950 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
5951 PDiag(diag::err_typecheck_incomplete_tag)
5952 << Base->getSourceRange()))
5953 return ExprError();
5954
John McCalla24dc2e2009-11-17 02:14:36 +00005955 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
5956 LookupQualifiedName(R, BaseRecord->getDecl());
5957 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00005958
5959 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00005960 Oper != OperEnd; ++Oper) {
5961 NamedDecl *D = *Oper;
5962 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5963 if (isa<UsingShadowDecl>(D))
5964 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5965
5966 AddMethodCandidate(cast<CXXMethodDecl>(D), ActingContext,
5967 Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00005968 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00005969 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00005970
5971 // Perform overload resolution.
5972 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005973 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00005974 case OR_Success:
5975 // Overload resolution succeeded; we'll build the call below.
5976 break;
5977
5978 case OR_No_Viable_Function:
5979 if (CandidateSet.empty())
5980 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005981 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005982 else
5983 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005984 << "operator->" << Base->getSourceRange();
John McCall81201622010-01-08 04:41:39 +00005985 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005986 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005987
5988 case OR_Ambiguous:
5989 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00005990 << "->" << Base->getSourceRange();
John McCall81201622010-01-08 04:41:39 +00005991 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005992 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005993
5994 case OR_Deleted:
5995 Diag(OpLoc, diag::err_ovl_deleted_oper)
5996 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00005997 << "->" << Base->getSourceRange();
John McCall81201622010-01-08 04:41:39 +00005998 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005999 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006000 }
6001
6002 // Convert the object parameter.
6003 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00006004 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006005 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00006006
6007 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006008 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006009
6010 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00006011 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6012 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00006013 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00006014
6015 QualType ResultTy = Method->getResultType().getNonReferenceType();
6016 ExprOwningPtr<CXXOperatorCallExpr>
6017 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6018 &Base, 1, ResultTy, OpLoc));
6019
6020 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6021 Method))
6022 return ExprError();
6023 return move(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00006024}
6025
Douglas Gregor904eed32008-11-10 20:40:00 +00006026/// FixOverloadedFunctionReference - E is an expression that refers to
6027/// a C++ overloaded function (possibly with some parentheses and
6028/// perhaps a '&' around it). We have resolved the overloaded function
6029/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00006030/// refer (possibly indirectly) to Fn. Returns the new expr.
6031Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006032 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor699ee522009-11-20 19:42:02 +00006033 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
6034 if (SubExpr == PE->getSubExpr())
6035 return PE->Retain();
6036
6037 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6038 }
6039
6040 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6041 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00006042 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00006043 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00006044 "Implicit cast type cannot be determined from overload");
Douglas Gregor699ee522009-11-20 19:42:02 +00006045 if (SubExpr == ICE->getSubExpr())
6046 return ICE->Retain();
6047
6048 return new (Context) ImplicitCastExpr(ICE->getType(),
6049 ICE->getCastKind(),
6050 SubExpr,
6051 ICE->isLvalueCast());
6052 }
6053
6054 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006055 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00006056 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00006057 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6058 if (Method->isStatic()) {
6059 // Do nothing: static member functions aren't any different
6060 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00006061 } else {
John McCallf7a1a742009-11-24 19:00:30 +00006062 // Fix the sub expression, which really has to be an
6063 // UnresolvedLookupExpr holding an overloaded member function
6064 // or template.
John McCallba135432009-11-21 08:51:07 +00006065 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6066 if (SubExpr == UnOp->getSubExpr())
6067 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00006068
John McCallba135432009-11-21 08:51:07 +00006069 assert(isa<DeclRefExpr>(SubExpr)
6070 && "fixed to something other than a decl ref");
6071 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6072 && "fixed to a member ref with no nested name qualifier");
6073
6074 // We have taken the address of a pointer to member
6075 // function. Perform the computation here so that we get the
6076 // appropriate pointer to member type.
6077 QualType ClassType
6078 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6079 QualType MemPtrType
6080 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6081
6082 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6083 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00006084 }
6085 }
Douglas Gregor699ee522009-11-20 19:42:02 +00006086 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6087 if (SubExpr == UnOp->getSubExpr())
6088 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00006089
Douglas Gregor699ee522009-11-20 19:42:02 +00006090 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6091 Context.getPointerType(SubExpr->getType()),
6092 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00006093 }
John McCallba135432009-11-21 08:51:07 +00006094
6095 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00006096 // FIXME: avoid copy.
6097 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00006098 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00006099 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6100 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00006101 }
6102
John McCallba135432009-11-21 08:51:07 +00006103 return DeclRefExpr::Create(Context,
6104 ULE->getQualifier(),
6105 ULE->getQualifierRange(),
6106 Fn,
6107 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00006108 Fn->getType(),
6109 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00006110 }
6111
John McCall129e2df2009-11-30 22:42:35 +00006112 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00006113 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00006114 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6115 if (MemExpr->hasExplicitTemplateArgs()) {
6116 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6117 TemplateArgs = &TemplateArgsBuffer;
6118 }
John McCalld5532b62009-11-23 01:53:49 +00006119
John McCallaa81e162009-12-01 22:10:20 +00006120 Expr *Base;
6121
6122 // If we're filling in
6123 if (MemExpr->isImplicitAccess()) {
6124 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6125 return DeclRefExpr::Create(Context,
6126 MemExpr->getQualifier(),
6127 MemExpr->getQualifierRange(),
6128 Fn,
6129 MemExpr->getMemberLoc(),
6130 Fn->getType(),
6131 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00006132 } else {
6133 SourceLocation Loc = MemExpr->getMemberLoc();
6134 if (MemExpr->getQualifier())
6135 Loc = MemExpr->getQualifierRange().getBegin();
6136 Base = new (Context) CXXThisExpr(Loc,
6137 MemExpr->getBaseType(),
6138 /*isImplicit=*/true);
6139 }
John McCallaa81e162009-12-01 22:10:20 +00006140 } else
6141 Base = MemExpr->getBase()->Retain();
6142
6143 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00006144 MemExpr->isArrow(),
6145 MemExpr->getQualifier(),
6146 MemExpr->getQualifierRange(),
6147 Fn,
John McCalld5532b62009-11-23 01:53:49 +00006148 MemExpr->getMemberLoc(),
John McCallaa81e162009-12-01 22:10:20 +00006149 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00006150 Fn->getType());
6151 }
6152
Douglas Gregor699ee522009-11-20 19:42:02 +00006153 assert(false && "Invalid reference to overloaded function");
6154 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00006155}
6156
Douglas Gregor20093b42009-12-09 23:02:17 +00006157Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
6158 FunctionDecl *Fn) {
6159 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
6160}
6161
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006162} // end namespace clang