blob: 26f8c8edda5ad111db827137e94a2b265f52b1aa [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000016#include "SemaInit.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000027#include <algorithm>
Torok Edwindb714922009-08-24 13:25:12 +000028#include <cstdio>
Douglas Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +000034ImplicitConversionCategory
Douglas Gregor5251f1b2008-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 Gregor40cb9ad2009-12-09 00:47:37 +000042 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000043 ICC_Qualification_Adjustment,
44 ICC_Promotion,
45 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000046 ICC_Promotion,
47 ICC_Conversion,
48 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000049 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
53 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000054 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000055 ICC_Conversion,
Douglas Gregor5251f1b2008-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 Gregor40cb9ad2009-12-09 00:47:37 +000071 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000072 ICR_Promotion,
73 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000074 ICR_Promotion,
75 ICR_Conversion,
76 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000077 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
81 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000082 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000083 ICR_Conversion,
Douglas Gregor5251f1b2008-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 Lopescfca1f02009-12-23 17:49:57 +000092 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000093 "No conversion",
94 "Lvalue-to-rvalue",
95 "Array-to-pointer",
96 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000097 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +000098 "Qualification",
99 "Integral promotion",
100 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000101 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000102 "Integral conversion",
103 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000104 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000105 "Floating-integral conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000106 "Complex-real conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000107 "Pointer conversion",
108 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000109 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000110 "Compatible-types conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000111 "Derived-to-base conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000112 };
113 return Name[Kind];
114}
115
Douglas Gregor26bee0b2008-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 Redlf69a94a2009-03-29 22:46:24 +0000125 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000126 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000127}
128
Douglas Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +0000145/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000146/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000147bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000148 // Note that FromType has not necessarily been transformed by the
149 // array-to-pointer or function-to-pointer implicit conversions, so
150 // check for their presence as well as checking whether FromType is
151 // a pointer.
John McCall0d1da222010-01-12 00:44:57 +0000152 if (getToType()->isBooleanType() &&
153 (getFromType()->isPointerType() || getFromType()->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000154 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
155 return true;
156
157 return false;
158}
159
Douglas Gregor5c407d92008-10-23 00:40:37 +0000160/// isPointerConversionToVoidPointer - Determines whether this
161/// conversion is a conversion of a pointer to a void pointer. This is
162/// used as part of the ranking of standard conversion sequences (C++
163/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000164bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000165StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000166isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000167 QualType FromType = getFromType();
168 QualType ToType = getToType();
Douglas Gregor5c407d92008-10-23 00:40:37 +0000169
170 // Note that FromType has not necessarily been transformed by the
171 // array-to-pointer implicit conversion, so check for its presence
172 // and redo the conversion to get a pointer.
173 if (First == ICK_Array_To_Pointer)
174 FromType = Context.getArrayDecayedType(FromType);
175
Douglas Gregor1aa450a2009-12-13 21:37:05 +0000176 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000177 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000178 return ToPtrType->getPointeeType()->isVoidType();
179
180 return false;
181}
182
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000183/// DebugPrint - Print this standard conversion sequence to standard
184/// error. Useful for debugging overloading issues.
185void StandardConversionSequence::DebugPrint() const {
186 bool PrintedSomething = false;
187 if (First != ICK_Identity) {
188 fprintf(stderr, "%s", GetImplicitConversionName(First));
189 PrintedSomething = true;
190 }
191
192 if (Second != ICK_Identity) {
193 if (PrintedSomething) {
194 fprintf(stderr, " -> ");
195 }
196 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor2fe98832008-11-03 19:09:14 +0000197
198 if (CopyConstructor) {
199 fprintf(stderr, " (by copy constructor)");
200 } else if (DirectBinding) {
201 fprintf(stderr, " (direct reference binding)");
202 } else if (ReferenceBinding) {
203 fprintf(stderr, " (reference binding)");
204 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205 PrintedSomething = true;
206 }
207
208 if (Third != ICK_Identity) {
209 if (PrintedSomething) {
210 fprintf(stderr, " -> ");
211 }
212 fprintf(stderr, "%s", GetImplicitConversionName(Third));
213 PrintedSomething = true;
214 }
215
216 if (!PrintedSomething) {
217 fprintf(stderr, "No conversions required");
218 }
219}
220
221/// DebugPrint - Print this user-defined conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void UserDefinedConversionSequence::DebugPrint() const {
224 if (Before.First || Before.Second || Before.Third) {
225 Before.DebugPrint();
226 fprintf(stderr, " -> ");
227 }
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000228 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000229 if (After.First || After.Second || After.Third) {
230 fprintf(stderr, " -> ");
231 After.DebugPrint();
232 }
233}
234
235/// DebugPrint - Print this implicit conversion sequence to standard
236/// error. Useful for debugging overloading issues.
237void ImplicitConversionSequence::DebugPrint() const {
238 switch (ConversionKind) {
239 case StandardConversion:
240 fprintf(stderr, "Standard conversion: ");
241 Standard.DebugPrint();
242 break;
243 case UserDefinedConversion:
244 fprintf(stderr, "User-defined conversion: ");
245 UserDefined.DebugPrint();
246 break;
247 case EllipsisConversion:
248 fprintf(stderr, "Ellipsis conversion");
249 break;
John McCall0d1da222010-01-12 00:44:57 +0000250 case AmbiguousConversion:
251 fprintf(stderr, "Ambiguous conversion");
252 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000253 case BadConversion:
254 fprintf(stderr, "Bad conversion");
255 break;
256 }
257
258 fprintf(stderr, "\n");
259}
260
John McCall0d1da222010-01-12 00:44:57 +0000261void AmbiguousConversionSequence::construct() {
262 new (&conversions()) ConversionSet();
263}
264
265void AmbiguousConversionSequence::destruct() {
266 conversions().~ConversionSet();
267}
268
269void
270AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
271 FromTypePtr = O.FromTypePtr;
272 ToTypePtr = O.ToTypePtr;
273 new (&conversions()) ConversionSet(O.conversions());
274}
275
276
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000277// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000278// overload of the declarations in Old. This routine returns false if
279// New and Old cannot be overloaded, e.g., if New has the same
280// signature as some function in Old (C++ 1.3.10) or if the Old
281// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000282// it does return false, MatchedDecl will point to the decl that New
283// cannot be overloaded with. This decl may be a UsingShadowDecl on
284// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000285//
286// Example: Given the following input:
287//
288// void f(int, float); // #1
289// void f(int, int); // #2
290// int f(int, int); // #3
291//
292// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000293// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000294//
John McCall3d988d92009-12-02 08:47:38 +0000295// When we process #2, Old contains only the FunctionDecl for #1. By
296// comparing the parameter types, we see that #1 and #2 are overloaded
297// (since they have different signatures), so this routine returns
298// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000299//
John McCall3d988d92009-12-02 08:47:38 +0000300// When we process #3, Old is an overload set containing #1 and #2. We
301// compare the signatures of #3 to #1 (they're overloaded, so we do
302// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
303// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000304// signature), IsOverload returns false and MatchedDecl will be set to
305// point to the FunctionDecl for #2.
John McCalldaa3d6b2009-12-09 03:35:25 +0000306Sema::OverloadKind
John McCall84d87672009-12-10 09:41:52 +0000307Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
308 NamedDecl *&Match) {
John McCall3d988d92009-12-02 08:47:38 +0000309 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000310 I != E; ++I) {
John McCall3d988d92009-12-02 08:47:38 +0000311 NamedDecl *OldD = (*I)->getUnderlyingDecl();
312 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000313 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000314 Match = *I;
315 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000316 }
John McCall3d988d92009-12-02 08:47:38 +0000317 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000318 if (!IsOverload(New, OldF)) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000319 Match = *I;
320 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000321 }
John McCall84d87672009-12-10 09:41:52 +0000322 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
323 // We can overload with these, which can show up when doing
324 // redeclaration checks for UsingDecls.
325 assert(Old.getLookupKind() == LookupUsingDeclName);
326 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
327 // Optimistically assume that an unresolved using decl will
328 // overload; if it doesn't, we'll have to diagnose during
329 // template instantiation.
330 } else {
John McCall1f82f242009-11-18 22:49:29 +0000331 // (C++ 13p1):
332 // Only function declarations can be overloaded; object and type
333 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000334 Match = *I;
335 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000336 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000337 }
John McCall1f82f242009-11-18 22:49:29 +0000338
John McCalldaa3d6b2009-12-09 03:35:25 +0000339 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000340}
341
342bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
343 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
344 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
345
346 // C++ [temp.fct]p2:
347 // A function template can be overloaded with other function templates
348 // and with normal (non-template) functions.
349 if ((OldTemplate == 0) != (NewTemplate == 0))
350 return true;
351
352 // Is the function New an overload of the function Old?
353 QualType OldQType = Context.getCanonicalType(Old->getType());
354 QualType NewQType = Context.getCanonicalType(New->getType());
355
356 // Compare the signatures (C++ 1.3.10) of the two functions to
357 // determine whether they are overloads. If we find any mismatch
358 // in the signature, they are overloads.
359
360 // If either of these functions is a K&R-style function (no
361 // prototype), then we consider them to have matching signatures.
362 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
363 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
364 return false;
365
366 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
367 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
368
369 // The signature of a function includes the types of its
370 // parameters (C++ 1.3.10), which includes the presence or absence
371 // of the ellipsis; see C++ DR 357).
372 if (OldQType != NewQType &&
373 (OldType->getNumArgs() != NewType->getNumArgs() ||
374 OldType->isVariadic() != NewType->isVariadic() ||
375 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
376 NewType->arg_type_begin())))
377 return true;
378
379 // C++ [temp.over.link]p4:
380 // The signature of a function template consists of its function
381 // signature, its return type and its template parameter list. The names
382 // of the template parameters are significant only for establishing the
383 // relationship between the template parameters and the rest of the
384 // signature.
385 //
386 // We check the return type and template parameter lists for function
387 // templates first; the remaining checks follow.
388 if (NewTemplate &&
389 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
390 OldTemplate->getTemplateParameters(),
391 false, TPL_TemplateMatch) ||
392 OldType->getResultType() != NewType->getResultType()))
393 return true;
394
395 // If the function is a class member, its signature includes the
396 // cv-qualifiers (if any) on the function itself.
397 //
398 // As part of this, also check whether one of the member functions
399 // is static, in which case they are not overloads (C++
400 // 13.1p2). While not part of the definition of the signature,
401 // this check is important to determine whether these functions
402 // can be overloaded.
403 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
404 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
405 if (OldMethod && NewMethod &&
406 !OldMethod->isStatic() && !NewMethod->isStatic() &&
407 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
408 return true;
409
410 // The signatures match; this is not an overload.
411 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000412}
413
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000414/// TryImplicitConversion - Attempt to perform an implicit conversion
415/// from the given expression (Expr) to the given type (ToType). This
416/// function returns an implicit conversion sequence that can be used
417/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000418///
419/// void f(float f);
420/// void g(int i) { f(i); }
421///
422/// this routine would produce an implicit conversion sequence to
423/// describe the initialization of f from i, which will be a standard
424/// conversion sequence containing an lvalue-to-rvalue conversion (C++
425/// 4.1) followed by a floating-integral conversion (C++ 4.9).
426//
427/// Note that this routine only determines how the conversion can be
428/// performed; it does not actually perform the conversion. As such,
429/// it will not produce any diagnostics if no conversion is available,
430/// but will instead return an implicit conversion sequence of kind
431/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000432///
433/// If @p SuppressUserConversions, then user-defined conversions are
434/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000435/// If @p AllowExplicit, then explicit user-defined conversions are
436/// permitted.
Sebastian Redl42e92c42009-04-12 17:16:29 +0000437/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
438/// no matter its actual lvalueness.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000439/// If @p UserCast, the implicit conversion is being done for a user-specified
440/// cast.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000441ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000442Sema::TryImplicitConversion(Expr* From, QualType ToType,
443 bool SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +0000444 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000445 bool InOverloadResolution,
446 bool UserCast) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000447 ImplicitConversionSequence ICS;
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000448 OverloadCandidateSet Conversions;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000449 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson228eea32009-08-28 15:33:32 +0000450 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
John McCall0d1da222010-01-12 00:44:57 +0000451 ICS.setStandard();
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000452 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000453 (UserDefResult = IsUserDefinedConversion(From, ToType,
454 ICS.UserDefined,
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000455 Conversions,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000456 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000457 ForceRValue, UserCast)) == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000458 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000459 // C++ [over.ics.user]p4:
460 // A conversion of an expression of class type to the same class
461 // type is given Exact Match rank, and a conversion of an
462 // expression of class type to a base class of that type is
463 // given Conversion rank, in spite of the fact that a copy
464 // constructor (i.e., a user-defined conversion function) is
465 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000466 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000467 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000468 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000469 = Context.getCanonicalType(From->getType().getUnqualifiedType());
470 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000471 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000472 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000473 // Turn this into a "standard" conversion sequence, so that it
474 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000475 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000476 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000477 ICS.Standard.setFromType(From->getType());
478 ICS.Standard.setToType(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000479 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000480 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000481 ICS.Standard.Second = ICK_Derived_To_Base;
482 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000483 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000484
485 // C++ [over.best.ics]p4:
486 // However, when considering the argument of a user-defined
487 // conversion function that is a candidate by 13.3.1.3 when
488 // invoked for the copying of the temporary in the second step
489 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
490 // 13.3.1.6 in all cases, only standard conversion sequences and
491 // ellipsis conversion sequences are allowed.
John McCall0d1da222010-01-12 00:44:57 +0000492 if (SuppressUserConversions && ICS.isUserDefined())
493 ICS.setBad();
494 } else if (UserDefResult == OR_Ambiguous) {
495 ICS.setAmbiguous();
496 ICS.Ambiguous.setFromType(From->getType());
497 ICS.Ambiguous.setToType(ToType);
498 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
499 Cand != Conversions.end(); ++Cand)
500 if (Cand->Viable)
501 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000502 } else {
John McCall0d1da222010-01-12 00:44:57 +0000503 ICS.setBad();
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000504 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000505
506 return ICS;
507}
508
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000509/// \brief Determine whether the conversion from FromType to ToType is a valid
510/// conversion that strips "noreturn" off the nested function type.
511static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
512 QualType ToType, QualType &ResultTy) {
513 if (Context.hasSameUnqualifiedType(FromType, ToType))
514 return false;
515
516 // Strip the noreturn off the type we're converting from; noreturn can
517 // safely be removed.
518 FromType = Context.getNoReturnType(FromType, false);
519 if (!Context.hasSameUnqualifiedType(FromType, ToType))
520 return false;
521
522 ResultTy = FromType;
523 return true;
524}
525
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000526/// IsStandardConversion - Determines whether there is a standard
527/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
528/// expression From to the type ToType. Standard conversion sequences
529/// only consider non-class types; for conversions that involve class
530/// types, use TryImplicitConversion. If a conversion exists, SCS will
531/// contain the standard conversion sequence required to perform this
532/// conversion and this routine will return true. Otherwise, this
533/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000534bool
535Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000536 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000537 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000538 QualType FromType = From->getType();
539
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000540 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000541 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000542 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000543 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000544 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000545 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000546
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000547 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000548 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000549 if (FromType->isRecordType() || ToType->isRecordType()) {
550 if (getLangOptions().CPlusPlus)
551 return false;
552
Mike Stump11289f42009-09-09 15:08:12 +0000553 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000554 }
555
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000556 // The first conversion can be an lvalue-to-rvalue conversion,
557 // array-to-pointer conversion, or function-to-pointer conversion
558 // (C++ 4p1).
559
Mike Stump11289f42009-09-09 15:08:12 +0000560 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000561 // An lvalue (3.10) of a non-function, non-array type T can be
562 // converted to an rvalue.
563 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000564 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000565 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000566 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000567 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000568
569 // If T is a non-class type, the type of the rvalue is the
570 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000571 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
572 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000573 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000574 } else if (FromType->isArrayType()) {
575 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000576 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000577
578 // An lvalue or rvalue of type "array of N T" or "array of unknown
579 // bound of T" can be converted to an rvalue of type "pointer to
580 // T" (C++ 4.2p1).
581 FromType = Context.getArrayDecayedType(FromType);
582
583 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
584 // This conversion is deprecated. (C++ D.4).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000585 SCS.Deprecated = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000586
587 // For the purpose of ranking in overload resolution
588 // (13.3.3.1.1), this conversion is considered an
589 // array-to-pointer conversion followed by a qualification
590 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000591 SCS.Second = ICK_Identity;
592 SCS.Third = ICK_Qualification;
John McCall0d1da222010-01-12 00:44:57 +0000593 SCS.setToType(ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000594 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000595 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000596 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
597 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000598 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000599
600 // An lvalue of function type T can be converted to an rvalue of
601 // type "pointer to T." The result is a pointer to the
602 // function. (C++ 4.3p1).
603 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000604 } else if (FunctionDecl *Fn
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000605 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000606 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000607 SCS.First = ICK_Function_To_Pointer;
608
609 // We were able to resolve the address of the overloaded function,
610 // so we can convert to the type of that function.
611 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000612 if (ToType->isLValueReferenceType())
613 FromType = Context.getLValueReferenceType(FromType);
614 else if (ToType->isRValueReferenceType())
615 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000616 else if (ToType->isMemberPointerType()) {
617 // Resolve address only succeeds if both sides are member pointers,
618 // but it doesn't have to be the same class. See DR 247.
619 // Note that this means that the type of &Derived::fn can be
620 // Ret (Base::*)(Args) if the fn overload actually found is from the
621 // base class, even if it was brought into the derived class via a
622 // using declaration. The standard isn't clear on this issue at all.
623 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
624 FromType = Context.getMemberPointerType(FromType,
625 Context.getTypeDeclType(M->getParent()).getTypePtr());
626 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000627 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000628 } else {
629 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000630 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000631 }
632
633 // The second conversion can be an integral promotion, floating
634 // point promotion, integral conversion, floating point conversion,
635 // floating-integral conversion, pointer conversion,
636 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000637 // For overloading in C, this can also be a "compatible-type"
638 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000639 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000640 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000641 // The unqualified versions of the types are the same: there's no
642 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000643 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000644 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000645 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000646 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000647 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000648 } else if (IsFloatingPointPromotion(FromType, ToType)) {
649 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000650 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000651 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000652 } else if (IsComplexPromotion(FromType, ToType)) {
653 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000654 SCS.Second = ICK_Complex_Promotion;
655 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000656 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000657 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000658 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000659 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000660 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000661 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
662 // Floating point conversions (C++ 4.8).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000663 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000664 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000665 } else if (FromType->isComplexType() && ToType->isComplexType()) {
666 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000667 SCS.Second = ICK_Complex_Conversion;
668 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000669 } else if ((FromType->isFloatingType() &&
670 ToType->isIntegralType() && (!ToType->isBooleanType() &&
671 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000672 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000673 ToType->isFloatingType())) {
674 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000675 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000676 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000677 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
678 (ToType->isComplexType() && FromType->isArithmeticType())) {
679 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000680 SCS.Second = ICK_Complex_Real;
681 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000682 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
683 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000684 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000685 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000686 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000687 } else if (IsMemberPointerConversion(From, FromType, ToType,
688 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000689 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000690 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000691 } else if (ToType->isBooleanType() &&
692 (FromType->isArithmeticType() ||
693 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +0000694 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +0000695 FromType->isBlockPointerType() ||
696 FromType->isMemberPointerType() ||
697 FromType->isNullPtrType())) {
698 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000699 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000700 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000701 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000702 Context.typesAreCompatible(ToType, FromType)) {
703 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000704 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000705 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
706 // Treat a conversion that strips "noreturn" as an identity conversion.
707 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000708 } else {
709 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000710 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000711 }
712
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000713 QualType CanonFrom;
714 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000715 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000716 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000717 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000718 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000719 CanonFrom = Context.getCanonicalType(FromType);
720 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000721 } else {
722 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000723 SCS.Third = ICK_Identity;
724
Mike Stump11289f42009-09-09 15:08:12 +0000725 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000726 // [...] Any difference in top-level cv-qualification is
727 // subsumed by the initialization itself and does not constitute
728 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000729 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000730 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000731 if (CanonFrom.getLocalUnqualifiedType()
732 == CanonTo.getLocalUnqualifiedType() &&
733 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000734 FromType = ToType;
735 CanonFrom = CanonTo;
736 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000737 }
738
739 // If we have not converted the argument type to the parameter type,
740 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000741 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000742 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000743
John McCall0d1da222010-01-12 00:44:57 +0000744 SCS.setToType(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000745 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000746}
747
748/// IsIntegralPromotion - Determines whether the conversion from the
749/// expression From (whose potentially-adjusted type is FromType) to
750/// ToType is an integral promotion (C++ 4.5). If so, returns true and
751/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000752bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000753 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000754 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000755 if (!To) {
756 return false;
757 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000758
759 // An rvalue of type char, signed char, unsigned char, short int, or
760 // unsigned short int can be converted to an rvalue of type int if
761 // int can represent all the values of the source type; otherwise,
762 // the source rvalue can be converted to an rvalue of type unsigned
763 // int (C++ 4.5p1).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000764 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000765 if (// We can promote any signed, promotable integer type to an int
766 (FromType->isSignedIntegerType() ||
767 // We can promote any unsigned integer type whose size is
768 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000769 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000770 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000771 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000772 }
773
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000774 return To->getKind() == BuiltinType::UInt;
775 }
776
777 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
778 // can be converted to an rvalue of the first of the following types
779 // that can represent all the values of its underlying type: int,
780 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +0000781
782 // We pre-calculate the promotion type for enum types.
783 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
784 if (ToType->isIntegerType())
785 return Context.hasSameUnqualifiedType(ToType,
786 FromEnumType->getDecl()->getPromotionType());
787
788 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000789 // Determine whether the type we're converting from is signed or
790 // unsigned.
791 bool FromIsSigned;
792 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +0000793
794 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
795 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000796
797 // The types we'll try to promote to, in the appropriate
798 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000799 QualType PromoteTypes[6] = {
800 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000801 Context.LongTy, Context.UnsignedLongTy ,
802 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000803 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000804 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000805 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
806 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000807 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000808 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
809 // We found the type that we can promote to. If this is the
810 // type we wanted, we have a promotion. Otherwise, no
811 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000812 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000813 }
814 }
815 }
816
817 // An rvalue for an integral bit-field (9.6) can be converted to an
818 // rvalue of type int if int can represent all the values of the
819 // bit-field; otherwise, it can be converted to unsigned int if
820 // unsigned int can represent all the values of the bit-field. If
821 // the bit-field is larger yet, no integral promotion applies to
822 // it. If the bit-field has an enumerated type, it is treated as any
823 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000824 // FIXME: We should delay checking of bit-fields until we actually perform the
825 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000826 using llvm::APSInt;
827 if (From)
828 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000829 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000830 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
831 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
832 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
833 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000834
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000835 // Are we promoting to an int from a bitfield that fits in an int?
836 if (BitWidth < ToSize ||
837 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
838 return To->getKind() == BuiltinType::Int;
839 }
Mike Stump11289f42009-09-09 15:08:12 +0000840
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000841 // Are we promoting to an unsigned int from an unsigned bitfield
842 // that fits into an unsigned int?
843 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
844 return To->getKind() == BuiltinType::UInt;
845 }
Mike Stump11289f42009-09-09 15:08:12 +0000846
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000847 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000848 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000849 }
Mike Stump11289f42009-09-09 15:08:12 +0000850
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000851 // An rvalue of type bool can be converted to an rvalue of type int,
852 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000853 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000854 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000855 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000856
857 return false;
858}
859
860/// IsFloatingPointPromotion - Determines whether the conversion from
861/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
862/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000863bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000864 /// An rvalue of type float can be converted to an rvalue of type
865 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000866 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
867 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000868 if (FromBuiltin->getKind() == BuiltinType::Float &&
869 ToBuiltin->getKind() == BuiltinType::Double)
870 return true;
871
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000872 // C99 6.3.1.5p1:
873 // When a float is promoted to double or long double, or a
874 // double is promoted to long double [...].
875 if (!getLangOptions().CPlusPlus &&
876 (FromBuiltin->getKind() == BuiltinType::Float ||
877 FromBuiltin->getKind() == BuiltinType::Double) &&
878 (ToBuiltin->getKind() == BuiltinType::LongDouble))
879 return true;
880 }
881
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000882 return false;
883}
884
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000885/// \brief Determine if a conversion is a complex promotion.
886///
887/// A complex promotion is defined as a complex -> complex conversion
888/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000889/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000890bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000891 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000892 if (!FromComplex)
893 return false;
894
John McCall9dd450b2009-09-21 23:43:11 +0000895 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000896 if (!ToComplex)
897 return false;
898
899 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000900 ToComplex->getElementType()) ||
901 IsIntegralPromotion(0, FromComplex->getElementType(),
902 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000903}
904
Douglas Gregor237f96c2008-11-26 23:31:11 +0000905/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
906/// the pointer type FromPtr to a pointer to type ToPointee, with the
907/// same type qualifiers as FromPtr has on its pointee type. ToType,
908/// if non-empty, will be a pointer to ToType that may or may not have
909/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000910static QualType
911BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000912 QualType ToPointee, QualType ToType,
913 ASTContext &Context) {
914 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
915 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000916 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000917
918 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000919 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000920 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000921 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000922 return ToType;
923
924 // Build a pointer to ToPointee. It has the right qualifiers
925 // already.
926 return Context.getPointerType(ToPointee);
927 }
928
929 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000930 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000931 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
932 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000933}
934
Fariborz Jahanian01cbe442009-12-16 23:13:33 +0000935/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
936/// the FromType, which is an objective-c pointer, to ToType, which may or may
937/// not have the right set of qualifiers.
938static QualType
939BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
940 QualType ToType,
941 ASTContext &Context) {
942 QualType CanonFromType = Context.getCanonicalType(FromType);
943 QualType CanonToType = Context.getCanonicalType(ToType);
944 Qualifiers Quals = CanonFromType.getQualifiers();
945
946 // Exact qualifier match -> return the pointer type we're converting to.
947 if (CanonToType.getLocalQualifiers() == Quals)
948 return ToType;
949
950 // Just build a canonical type that has the right qualifiers.
951 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
952}
953
Mike Stump11289f42009-09-09 15:08:12 +0000954static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000955 bool InOverloadResolution,
956 ASTContext &Context) {
957 // Handle value-dependent integral null pointer constants correctly.
958 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
959 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
960 Expr->getType()->isIntegralType())
961 return !InOverloadResolution;
962
Douglas Gregor56751b52009-09-25 04:25:58 +0000963 return Expr->isNullPointerConstant(Context,
964 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
965 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +0000966}
Mike Stump11289f42009-09-09 15:08:12 +0000967
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000968/// IsPointerConversion - Determines whether the conversion of the
969/// expression From, which has the (possibly adjusted) type FromType,
970/// can be converted to the type ToType via a pointer conversion (C++
971/// 4.10). If so, returns true and places the converted type (that
972/// might differ from ToType in its cv-qualifiers at some level) into
973/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000974///
Douglas Gregora29dc052008-11-27 01:19:21 +0000975/// This routine also supports conversions to and from block pointers
976/// and conversions with Objective-C's 'id', 'id<protocols...>', and
977/// pointers to interfaces. FIXME: Once we've determined the
978/// appropriate overloading rules for Objective-C, we may want to
979/// split the Objective-C checks into a different routine; however,
980/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000981/// conversions, so for now they live here. IncompatibleObjC will be
982/// set if the conversion is an allowed Objective-C conversion that
983/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000984bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000985 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000986 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +0000987 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +0000988 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +0000989 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
990 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000991
Mike Stump11289f42009-09-09 15:08:12 +0000992 // Conversion from a null pointer constant to any Objective-C pointer type.
993 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000994 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +0000995 ConvertedType = ToType;
996 return true;
997 }
998
Douglas Gregor231d1c62008-11-27 00:15:41 +0000999 // Blocks: Block pointers can be converted to void*.
1000 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001001 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001002 ConvertedType = ToType;
1003 return true;
1004 }
1005 // Blocks: A null pointer constant can be converted to a block
1006 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001007 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001008 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001009 ConvertedType = ToType;
1010 return true;
1011 }
1012
Sebastian Redl576fd422009-05-10 18:38:11 +00001013 // If the left-hand-side is nullptr_t, the right side can be a null
1014 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001015 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001016 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001017 ConvertedType = ToType;
1018 return true;
1019 }
1020
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001021 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001022 if (!ToTypePtr)
1023 return false;
1024
1025 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001026 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001027 ConvertedType = ToType;
1028 return true;
1029 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001030
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001031 // Beyond this point, both types need to be pointers
1032 // , including objective-c pointers.
1033 QualType ToPointeeType = ToTypePtr->getPointeeType();
1034 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1035 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1036 ToType, Context);
1037 return true;
1038
1039 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001040 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001041 if (!FromTypePtr)
1042 return false;
1043
1044 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001045
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001046 // An rvalue of type "pointer to cv T," where T is an object type,
1047 // can be converted to an rvalue of type "pointer to cv void" (C++
1048 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001049 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001050 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001051 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001052 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001053 return true;
1054 }
1055
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001056 // When we're overloading in C, we allow a special kind of pointer
1057 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001058 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001059 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001060 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001061 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001062 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001063 return true;
1064 }
1065
Douglas Gregor5c407d92008-10-23 00:40:37 +00001066 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001067 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001068 // An rvalue of type "pointer to cv D," where D is a class type,
1069 // can be converted to an rvalue of type "pointer to cv B," where
1070 // B is a base class (clause 10) of D. If B is an inaccessible
1071 // (clause 11) or ambiguous (10.2) base class of D, a program that
1072 // necessitates this conversion is ill-formed. The result of the
1073 // conversion is a pointer to the base class sub-object of the
1074 // derived class object. The null pointer value is converted to
1075 // the null pointer value of the destination type.
1076 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001077 // Note that we do not check for ambiguity or inaccessibility
1078 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001079 if (getLangOptions().CPlusPlus &&
1080 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001081 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001082 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001083 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001084 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001085 ToType, Context);
1086 return true;
1087 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001088
Douglas Gregora119f102008-12-19 19:13:09 +00001089 return false;
1090}
1091
1092/// isObjCPointerConversion - Determines whether this is an
1093/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1094/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001095bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001096 QualType& ConvertedType,
1097 bool &IncompatibleObjC) {
1098 if (!getLangOptions().ObjC1)
1099 return false;
1100
Steve Naroff7cae42b2009-07-10 23:34:53 +00001101 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001102 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001103 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001104 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001105
Steve Naroff7cae42b2009-07-10 23:34:53 +00001106 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001107 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001108 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001109 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001110 ConvertedType = ToType;
1111 return true;
1112 }
1113 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001114 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001115 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001116 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001117 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001118 ConvertedType = ToType;
1119 return true;
1120 }
1121 // Objective C++: We're able to convert from a pointer to an
1122 // interface to a pointer to a different interface.
1123 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1124 ConvertedType = ToType;
1125 return true;
1126 }
1127
1128 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1129 // Okay: this is some kind of implicit downcast of Objective-C
1130 // interfaces, which is permitted. However, we're going to
1131 // complain about it.
1132 IncompatibleObjC = true;
1133 ConvertedType = FromType;
1134 return true;
1135 }
Mike Stump11289f42009-09-09 15:08:12 +00001136 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001137 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001138 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001139 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001140 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001141 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001142 ToPointeeType = ToBlockPtr->getPointeeType();
1143 else
Douglas Gregora119f102008-12-19 19:13:09 +00001144 return false;
1145
Douglas Gregor033f56d2008-12-23 00:53:59 +00001146 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001147 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001148 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001149 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001150 FromPointeeType = FromBlockPtr->getPointeeType();
1151 else
Douglas Gregora119f102008-12-19 19:13:09 +00001152 return false;
1153
Douglas Gregora119f102008-12-19 19:13:09 +00001154 // If we have pointers to pointers, recursively check whether this
1155 // is an Objective-C conversion.
1156 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1157 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1158 IncompatibleObjC)) {
1159 // We always complain about this conversion.
1160 IncompatibleObjC = true;
1161 ConvertedType = ToType;
1162 return true;
1163 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001164 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001165 // differences in the argument and result types are in Objective-C
1166 // pointer conversions. If so, we permit the conversion (but
1167 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001168 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001169 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001170 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001171 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001172 if (FromFunctionType && ToFunctionType) {
1173 // If the function types are exactly the same, this isn't an
1174 // Objective-C pointer conversion.
1175 if (Context.getCanonicalType(FromPointeeType)
1176 == Context.getCanonicalType(ToPointeeType))
1177 return false;
1178
1179 // Perform the quick checks that will tell us whether these
1180 // function types are obviously different.
1181 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1182 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1183 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1184 return false;
1185
1186 bool HasObjCConversion = false;
1187 if (Context.getCanonicalType(FromFunctionType->getResultType())
1188 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1189 // Okay, the types match exactly. Nothing to do.
1190 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1191 ToFunctionType->getResultType(),
1192 ConvertedType, IncompatibleObjC)) {
1193 // Okay, we have an Objective-C pointer conversion.
1194 HasObjCConversion = true;
1195 } else {
1196 // Function types are too different. Abort.
1197 return false;
1198 }
Mike Stump11289f42009-09-09 15:08:12 +00001199
Douglas Gregora119f102008-12-19 19:13:09 +00001200 // Check argument types.
1201 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1202 ArgIdx != NumArgs; ++ArgIdx) {
1203 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1204 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1205 if (Context.getCanonicalType(FromArgType)
1206 == Context.getCanonicalType(ToArgType)) {
1207 // Okay, the types match exactly. Nothing to do.
1208 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1209 ConvertedType, IncompatibleObjC)) {
1210 // Okay, we have an Objective-C pointer conversion.
1211 HasObjCConversion = true;
1212 } else {
1213 // Argument types are too different. Abort.
1214 return false;
1215 }
1216 }
1217
1218 if (HasObjCConversion) {
1219 // We had an Objective-C conversion. Allow this pointer
1220 // conversion, but complain about it.
1221 ConvertedType = ToType;
1222 IncompatibleObjC = true;
1223 return true;
1224 }
1225 }
1226
Sebastian Redl72b597d2009-01-25 19:43:20 +00001227 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001228}
1229
Douglas Gregor39c16d42008-10-24 04:54:22 +00001230/// CheckPointerConversion - Check the pointer conversion from the
1231/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001232/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001233/// conversions for which IsPointerConversion has already returned
1234/// true. It returns true and produces a diagnostic if there was an
1235/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001236bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001237 CastExpr::CastKind &Kind,
1238 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001239 QualType FromType = From->getType();
1240
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001241 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1242 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001243 QualType FromPointeeType = FromPtrType->getPointeeType(),
1244 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001245
Douglas Gregor39c16d42008-10-24 04:54:22 +00001246 if (FromPointeeType->isRecordType() &&
1247 ToPointeeType->isRecordType()) {
1248 // We must have a derived-to-base conversion. Check an
1249 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001250 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1251 From->getExprLoc(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001252 From->getSourceRange(),
1253 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001254 return true;
1255
1256 // The conversion was successful.
1257 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001258 }
1259 }
Mike Stump11289f42009-09-09 15:08:12 +00001260 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001261 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001262 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001263 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001264 // Objective-C++ conversions are always okay.
1265 // FIXME: We should have a different class of conversions for the
1266 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001267 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001268 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001269
Steve Naroff7cae42b2009-07-10 23:34:53 +00001270 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001271 return false;
1272}
1273
Sebastian Redl72b597d2009-01-25 19:43:20 +00001274/// IsMemberPointerConversion - Determines whether the conversion of the
1275/// expression From, which has the (possibly adjusted) type FromType, can be
1276/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1277/// If so, returns true and places the converted type (that might differ from
1278/// ToType in its cv-qualifiers at some level) into ConvertedType.
1279bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001280 QualType ToType,
1281 bool InOverloadResolution,
1282 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001283 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001284 if (!ToTypePtr)
1285 return false;
1286
1287 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001288 if (From->isNullPointerConstant(Context,
1289 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1290 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001291 ConvertedType = ToType;
1292 return true;
1293 }
1294
1295 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001296 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001297 if (!FromTypePtr)
1298 return false;
1299
1300 // A pointer to member of B can be converted to a pointer to member of D,
1301 // where D is derived from B (C++ 4.11p2).
1302 QualType FromClass(FromTypePtr->getClass(), 0);
1303 QualType ToClass(ToTypePtr->getClass(), 0);
1304 // FIXME: What happens when these are dependent? Is this function even called?
1305
1306 if (IsDerivedFrom(ToClass, FromClass)) {
1307 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1308 ToClass.getTypePtr());
1309 return true;
1310 }
1311
1312 return false;
1313}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001314
Sebastian Redl72b597d2009-01-25 19:43:20 +00001315/// CheckMemberPointerConversion - Check the member pointer conversion from the
1316/// expression From to the type ToType. This routine checks for ambiguous or
1317/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1318/// for which IsMemberPointerConversion has already returned true. It returns
1319/// true and produces a diagnostic if there was an error, or returns false
1320/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001321bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001322 CastExpr::CastKind &Kind,
1323 bool IgnoreBaseAccess) {
1324 (void)IgnoreBaseAccess;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001325 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001326 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001327 if (!FromPtrType) {
1328 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001329 assert(From->isNullPointerConstant(Context,
1330 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001331 "Expr must be null pointer constant!");
1332 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001333 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001334 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001335
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001336 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001337 assert(ToPtrType && "No member pointer cast has a target type "
1338 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001339
Sebastian Redled8f2002009-01-28 18:33:18 +00001340 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1341 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001342
Sebastian Redled8f2002009-01-28 18:33:18 +00001343 // FIXME: What about dependent types?
1344 assert(FromClass->isRecordType() && "Pointer into non-class.");
1345 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001346
Douglas Gregor36d1b142009-10-06 17:59:45 +00001347 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1348 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001349 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1350 assert(DerivationOkay &&
1351 "Should not have been called if derivation isn't OK.");
1352 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001353
Sebastian Redled8f2002009-01-28 18:33:18 +00001354 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1355 getUnqualifiedType())) {
1356 // Derivation is ambiguous. Redo the check to find the exact paths.
1357 Paths.clear();
1358 Paths.setRecordingPaths(true);
1359 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1360 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1361 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001362
Sebastian Redled8f2002009-01-28 18:33:18 +00001363 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1364 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1365 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1366 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001367 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001368
Douglas Gregor89ee6822009-02-28 01:32:25 +00001369 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001370 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1371 << FromClass << ToClass << QualType(VBase, 0)
1372 << From->getSourceRange();
1373 return true;
1374 }
1375
Anders Carlssond7923c62009-08-22 23:33:40 +00001376 // Must be a base to derived member conversion.
1377 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001378 return false;
1379}
1380
Douglas Gregor9a657932008-10-21 23:43:52 +00001381/// IsQualificationConversion - Determines whether the conversion from
1382/// an rvalue of type FromType to ToType is a qualification conversion
1383/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001384bool
1385Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001386 FromType = Context.getCanonicalType(FromType);
1387 ToType = Context.getCanonicalType(ToType);
1388
1389 // If FromType and ToType are the same type, this is not a
1390 // qualification conversion.
1391 if (FromType == ToType)
1392 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001393
Douglas Gregor9a657932008-10-21 23:43:52 +00001394 // (C++ 4.4p4):
1395 // A conversion can add cv-qualifiers at levels other than the first
1396 // in multi-level pointers, subject to the following rules: [...]
1397 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001398 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001399 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001400 // Within each iteration of the loop, we check the qualifiers to
1401 // determine if this still looks like a qualification
1402 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001403 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001404 // until there are no more pointers or pointers-to-members left to
1405 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001406 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001407
1408 // -- for every j > 0, if const is in cv 1,j then const is in cv
1409 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001410 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001411 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001412
Douglas Gregor9a657932008-10-21 23:43:52 +00001413 // -- if the cv 1,j and cv 2,j are different, then const is in
1414 // every cv for 0 < k < j.
1415 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001416 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001417 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001418
Douglas Gregor9a657932008-10-21 23:43:52 +00001419 // Keep track of whether all prior cv-qualifiers in the "to" type
1420 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001421 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001422 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001423 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001424
1425 // We are left with FromType and ToType being the pointee types
1426 // after unwrapping the original FromType and ToType the same number
1427 // of types. If we unwrapped any pointers, and if FromType and
1428 // ToType have the same unqualified type (since we checked
1429 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001430 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001431}
1432
Douglas Gregor576e98c2009-01-30 23:27:23 +00001433/// Determines whether there is a user-defined conversion sequence
1434/// (C++ [over.ics.user]) that converts expression From to the type
1435/// ToType. If such a conversion exists, User will contain the
1436/// user-defined conversion sequence that performs such a conversion
1437/// and this routine will return true. Otherwise, this routine returns
1438/// false and User is unspecified.
1439///
1440/// \param AllowConversionFunctions true if the conversion should
1441/// consider conversion functions at all. If false, only constructors
1442/// will be considered.
1443///
1444/// \param AllowExplicit true if the conversion should consider C++0x
1445/// "explicit" conversion functions as well as non-explicit conversion
1446/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001447///
1448/// \param ForceRValue true if the expression should be treated as an rvalue
1449/// for overload resolution.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001450/// \param UserCast true if looking for user defined conversion for a static
1451/// cast.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001452OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1453 UserDefinedConversionSequence& User,
1454 OverloadCandidateSet& CandidateSet,
1455 bool AllowConversionFunctions,
1456 bool AllowExplicit,
1457 bool ForceRValue,
1458 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001459 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001460 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1461 // We're not going to find any constructors.
1462 } else if (CXXRecordDecl *ToRecordDecl
1463 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001464 // C++ [over.match.ctor]p1:
1465 // When objects of class type are direct-initialized (8.5), or
1466 // copy-initialized from an expression of the same or a
1467 // derived class type (8.5), overload resolution selects the
1468 // constructor. [...] For copy-initialization, the candidate
1469 // functions are all the converting constructors (12.3.1) of
1470 // that class. The argument list is the expression-list within
1471 // the parentheses of the initializer.
Douglas Gregor379d84b2009-11-13 18:44:21 +00001472 bool SuppressUserConversions = !UserCast;
1473 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1474 IsDerivedFrom(From->getType(), ToType)) {
1475 SuppressUserConversions = false;
1476 AllowConversionFunctions = false;
1477 }
1478
Mike Stump11289f42009-09-09 15:08:12 +00001479 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001480 = Context.DeclarationNames.getCXXConstructorName(
1481 Context.getCanonicalType(ToType).getUnqualifiedType());
1482 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001483 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001484 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001485 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001486 // Find the constructor (which may be a template).
1487 CXXConstructorDecl *Constructor = 0;
1488 FunctionTemplateDecl *ConstructorTmpl
1489 = dyn_cast<FunctionTemplateDecl>(*Con);
1490 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001491 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001492 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1493 else
1494 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001495
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001496 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001497 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001498 if (ConstructorTmpl)
John McCall6b51f282009-11-23 01:53:49 +00001499 AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
1500 &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001501 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001502 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001503 // Allow one user-defined conversion when user specifies a
1504 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001505 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001506 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001507 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001508 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001509 }
1510 }
1511
Douglas Gregor576e98c2009-01-30 23:27:23 +00001512 if (!AllowConversionFunctions) {
1513 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001514 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1515 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001516 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001517 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001518 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001519 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001520 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001521 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1522 // Add all of the conversion functions as candidates.
John McCalld14a8642009-11-21 08:51:07 +00001523 const UnresolvedSet *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001524 = FromRecordDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00001525 for (UnresolvedSet::iterator I = Conversions->begin(),
1526 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00001527 NamedDecl *D = *I;
1528 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1529 if (isa<UsingShadowDecl>(D))
1530 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1531
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001532 CXXConversionDecl *Conv;
1533 FunctionTemplateDecl *ConvTemplate;
John McCalld14a8642009-11-21 08:51:07 +00001534 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001535 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1536 else
John McCalld14a8642009-11-21 08:51:07 +00001537 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001538
1539 if (AllowExplicit || !Conv->isExplicit()) {
1540 if (ConvTemplate)
John McCall6e9f8f62009-12-03 04:06:58 +00001541 AddTemplateConversionCandidate(ConvTemplate, ActingContext,
1542 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001543 else
John McCall6e9f8f62009-12-03 04:06:58 +00001544 AddConversionCandidate(Conv, ActingContext, From, ToType,
1545 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001546 }
1547 }
1548 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001549 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001550
1551 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001552 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001553 case OR_Success:
1554 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001555 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001556 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1557 // C++ [over.ics.user]p1:
1558 // If the user-defined conversion is specified by a
1559 // constructor (12.3.1), the initial standard conversion
1560 // sequence converts the source type to the type required by
1561 // the argument of the constructor.
1562 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001563 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001564 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001565 User.EllipsisConversion = true;
1566 else {
1567 User.Before = Best->Conversions[0].Standard;
1568 User.EllipsisConversion = false;
1569 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001570 User.ConversionFunction = Constructor;
1571 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001572 User.After.setFromType(
1573 ThisType->getAs<PointerType>()->getPointeeType());
1574 User.After.setToType(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001575 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001576 } else if (CXXConversionDecl *Conversion
1577 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1578 // C++ [over.ics.user]p1:
1579 //
1580 // [...] If the user-defined conversion is specified by a
1581 // conversion function (12.3.2), the initial standard
1582 // conversion sequence converts the source type to the
1583 // implicit object parameter of the conversion function.
1584 User.Before = Best->Conversions[0].Standard;
1585 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001586 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001587
1588 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001589 // The second standard conversion sequence converts the
1590 // result of the user-defined conversion to the target type
1591 // for the sequence. Since an implicit conversion sequence
1592 // is an initialization, the special rules for
1593 // initialization by user-defined conversion apply when
1594 // selecting the best user-defined conversion for a
1595 // user-defined conversion sequence (see 13.3.3 and
1596 // 13.3.3.1).
1597 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001598 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001599 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001600 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001601 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001602 }
Mike Stump11289f42009-09-09 15:08:12 +00001603
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001604 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001605 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001606 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001607 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001608 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001609
1610 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001611 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001612 }
1613
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001614 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001615}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001616
1617bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001618Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001619 ImplicitConversionSequence ICS;
1620 OverloadCandidateSet CandidateSet;
1621 OverloadingResult OvResult =
1622 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1623 CandidateSet, true, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001624 if (OvResult == OR_Ambiguous)
1625 Diag(From->getSourceRange().getBegin(),
1626 diag::err_typecheck_ambiguous_condition)
1627 << From->getType() << ToType << From->getSourceRange();
1628 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1629 Diag(From->getSourceRange().getBegin(),
1630 diag::err_typecheck_nonviable_condition)
1631 << From->getType() << ToType << From->getSourceRange();
1632 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001633 return false;
John McCall12f97bc2010-01-08 04:41:39 +00001634 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001635 return true;
1636}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001637
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001638/// CompareImplicitConversionSequences - Compare two implicit
1639/// conversion sequences to determine whether one is better than the
1640/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001641ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001642Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1643 const ImplicitConversionSequence& ICS2)
1644{
1645 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1646 // conversion sequences (as defined in 13.3.3.1)
1647 // -- a standard conversion sequence (13.3.3.1.1) is a better
1648 // conversion sequence than a user-defined conversion sequence or
1649 // an ellipsis conversion sequence, and
1650 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1651 // conversion sequence than an ellipsis conversion sequence
1652 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001653 //
John McCall0d1da222010-01-12 00:44:57 +00001654 // C++0x [over.best.ics]p10:
1655 // For the purpose of ranking implicit conversion sequences as
1656 // described in 13.3.3.2, the ambiguous conversion sequence is
1657 // treated as a user-defined sequence that is indistinguishable
1658 // from any other user-defined conversion sequence.
1659 if (ICS1.getKind() < ICS2.getKind()) {
1660 if (!(ICS1.isUserDefined() && ICS2.isAmbiguous()))
1661 return ImplicitConversionSequence::Better;
1662 } else if (ICS2.getKind() < ICS1.getKind()) {
1663 if (!(ICS2.isUserDefined() && ICS1.isAmbiguous()))
1664 return ImplicitConversionSequence::Worse;
1665 }
1666
1667 if (ICS1.isAmbiguous() || ICS2.isAmbiguous())
1668 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001669
1670 // Two implicit conversion sequences of the same form are
1671 // indistinguishable conversion sequences unless one of the
1672 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00001673 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001674 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00001675 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001676 // User-defined conversion sequence U1 is a better conversion
1677 // sequence than another user-defined conversion sequence U2 if
1678 // they contain the same user-defined conversion function or
1679 // constructor and if the second standard conversion sequence of
1680 // U1 is better than the second standard conversion sequence of
1681 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001682 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001683 ICS2.UserDefined.ConversionFunction)
1684 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1685 ICS2.UserDefined.After);
1686 }
1687
1688 return ImplicitConversionSequence::Indistinguishable;
1689}
1690
1691/// CompareStandardConversionSequences - Compare two standard
1692/// conversion sequences to determine whether one is better than the
1693/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001694ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001695Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1696 const StandardConversionSequence& SCS2)
1697{
1698 // Standard conversion sequence S1 is a better conversion sequence
1699 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1700
1701 // -- S1 is a proper subsequence of S2 (comparing the conversion
1702 // sequences in the canonical form defined by 13.3.3.1.1,
1703 // excluding any Lvalue Transformation; the identity conversion
1704 // sequence is considered to be a subsequence of any
1705 // non-identity conversion sequence) or, if not that,
1706 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1707 // Neither is a proper subsequence of the other. Do nothing.
1708 ;
1709 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1710 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001711 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001712 SCS1.Third == ICK_Identity))
1713 // SCS1 is a proper subsequence of SCS2.
1714 return ImplicitConversionSequence::Better;
1715 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1716 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001717 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001718 SCS2.Third == ICK_Identity))
1719 // SCS2 is a proper subsequence of SCS1.
1720 return ImplicitConversionSequence::Worse;
1721
1722 // -- the rank of S1 is better than the rank of S2 (by the rules
1723 // defined below), or, if not that,
1724 ImplicitConversionRank Rank1 = SCS1.getRank();
1725 ImplicitConversionRank Rank2 = SCS2.getRank();
1726 if (Rank1 < Rank2)
1727 return ImplicitConversionSequence::Better;
1728 else if (Rank2 < Rank1)
1729 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001730
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001731 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1732 // are indistinguishable unless one of the following rules
1733 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001734
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001735 // A conversion that is not a conversion of a pointer, or
1736 // pointer to member, to bool is better than another conversion
1737 // that is such a conversion.
1738 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1739 return SCS2.isPointerConversionToBool()
1740 ? ImplicitConversionSequence::Better
1741 : ImplicitConversionSequence::Worse;
1742
Douglas Gregor5c407d92008-10-23 00:40:37 +00001743 // C++ [over.ics.rank]p4b2:
1744 //
1745 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001746 // conversion of B* to A* is better than conversion of B* to
1747 // void*, and conversion of A* to void* is better than conversion
1748 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001749 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001750 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001751 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001752 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001753 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1754 // Exactly one of the conversion sequences is a conversion to
1755 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001756 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1757 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001758 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1759 // Neither conversion sequence converts to a void pointer; compare
1760 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001761 if (ImplicitConversionSequence::CompareKind DerivedCK
1762 = CompareDerivedToBaseConversions(SCS1, SCS2))
1763 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001764 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1765 // Both conversion sequences are conversions to void
1766 // pointers. Compare the source types to determine if there's an
1767 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00001768 QualType FromType1 = SCS1.getFromType();
1769 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001770
1771 // Adjust the types we're converting from via the array-to-pointer
1772 // conversion, if we need to.
1773 if (SCS1.First == ICK_Array_To_Pointer)
1774 FromType1 = Context.getArrayDecayedType(FromType1);
1775 if (SCS2.First == ICK_Array_To_Pointer)
1776 FromType2 = Context.getArrayDecayedType(FromType2);
1777
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001778 QualType FromPointee1
1779 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1780 QualType FromPointee2
1781 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001782
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001783 if (IsDerivedFrom(FromPointee2, FromPointee1))
1784 return ImplicitConversionSequence::Better;
1785 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1786 return ImplicitConversionSequence::Worse;
1787
1788 // Objective-C++: If one interface is more specific than the
1789 // other, it is the better one.
1790 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1791 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1792 if (FromIface1 && FromIface1) {
1793 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1794 return ImplicitConversionSequence::Better;
1795 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1796 return ImplicitConversionSequence::Worse;
1797 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001798 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001799
1800 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1801 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001802 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001803 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001804 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001805
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001806 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001807 // C++0x [over.ics.rank]p3b4:
1808 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1809 // implicit object parameter of a non-static member function declared
1810 // without a ref-qualifier, and S1 binds an rvalue reference to an
1811 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001812 // FIXME: We don't know if we're dealing with the implicit object parameter,
1813 // or if the member function in this case has a ref qualifier.
1814 // (Of course, we don't have ref qualifiers yet.)
1815 if (SCS1.RRefBinding != SCS2.RRefBinding)
1816 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1817 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001818
1819 // C++ [over.ics.rank]p3b4:
1820 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1821 // which the references refer are the same type except for
1822 // top-level cv-qualifiers, and the type to which the reference
1823 // initialized by S2 refers is more cv-qualified than the type
1824 // to which the reference initialized by S1 refers.
John McCall0d1da222010-01-12 00:44:57 +00001825 QualType T1 = SCS1.getToType();
1826 QualType T2 = SCS2.getToType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001827 T1 = Context.getCanonicalType(T1);
1828 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001829 Qualifiers T1Quals, T2Quals;
1830 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1831 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1832 if (UnqualT1 == UnqualT2) {
1833 // If the type is an array type, promote the element qualifiers to the type
1834 // for comparison.
1835 if (isa<ArrayType>(T1) && T1Quals)
1836 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1837 if (isa<ArrayType>(T2) && T2Quals)
1838 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001839 if (T2.isMoreQualifiedThan(T1))
1840 return ImplicitConversionSequence::Better;
1841 else if (T1.isMoreQualifiedThan(T2))
1842 return ImplicitConversionSequence::Worse;
1843 }
1844 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001845
1846 return ImplicitConversionSequence::Indistinguishable;
1847}
1848
1849/// CompareQualificationConversions - Compares two standard conversion
1850/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001851/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1852ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001853Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001854 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001855 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001856 // -- S1 and S2 differ only in their qualification conversion and
1857 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1858 // cv-qualification signature of type T1 is a proper subset of
1859 // the cv-qualification signature of type T2, and S1 is not the
1860 // deprecated string literal array-to-pointer conversion (4.2).
1861 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1862 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1863 return ImplicitConversionSequence::Indistinguishable;
1864
1865 // FIXME: the example in the standard doesn't use a qualification
1866 // conversion (!)
1867 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1868 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1869 T1 = Context.getCanonicalType(T1);
1870 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001871 Qualifiers T1Quals, T2Quals;
1872 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1873 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001874
1875 // If the types are the same, we won't learn anything by unwrapped
1876 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00001877 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001878 return ImplicitConversionSequence::Indistinguishable;
1879
Chandler Carruth607f38e2009-12-29 07:16:59 +00001880 // If the type is an array type, promote the element qualifiers to the type
1881 // for comparison.
1882 if (isa<ArrayType>(T1) && T1Quals)
1883 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1884 if (isa<ArrayType>(T2) && T2Quals)
1885 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1886
Mike Stump11289f42009-09-09 15:08:12 +00001887 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001888 = ImplicitConversionSequence::Indistinguishable;
1889 while (UnwrapSimilarPointerTypes(T1, T2)) {
1890 // Within each iteration of the loop, we check the qualifiers to
1891 // determine if this still looks like a qualification
1892 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001893 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001894 // until there are no more pointers or pointers-to-members left
1895 // to unwrap. This essentially mimics what
1896 // IsQualificationConversion does, but here we're checking for a
1897 // strict subset of qualifiers.
1898 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1899 // The qualifiers are the same, so this doesn't tell us anything
1900 // about how the sequences rank.
1901 ;
1902 else if (T2.isMoreQualifiedThan(T1)) {
1903 // T1 has fewer qualifiers, so it could be the better sequence.
1904 if (Result == ImplicitConversionSequence::Worse)
1905 // Neither has qualifiers that are a subset of the other's
1906 // qualifiers.
1907 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001908
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001909 Result = ImplicitConversionSequence::Better;
1910 } else if (T1.isMoreQualifiedThan(T2)) {
1911 // T2 has fewer qualifiers, so it could be the better sequence.
1912 if (Result == ImplicitConversionSequence::Better)
1913 // Neither has qualifiers that are a subset of the other's
1914 // qualifiers.
1915 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001916
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001917 Result = ImplicitConversionSequence::Worse;
1918 } else {
1919 // Qualifiers are disjoint.
1920 return ImplicitConversionSequence::Indistinguishable;
1921 }
1922
1923 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001924 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001925 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001926 }
1927
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001928 // Check that the winning standard conversion sequence isn't using
1929 // the deprecated string literal array to pointer conversion.
1930 switch (Result) {
1931 case ImplicitConversionSequence::Better:
1932 if (SCS1.Deprecated)
1933 Result = ImplicitConversionSequence::Indistinguishable;
1934 break;
1935
1936 case ImplicitConversionSequence::Indistinguishable:
1937 break;
1938
1939 case ImplicitConversionSequence::Worse:
1940 if (SCS2.Deprecated)
1941 Result = ImplicitConversionSequence::Indistinguishable;
1942 break;
1943 }
1944
1945 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001946}
1947
Douglas Gregor5c407d92008-10-23 00:40:37 +00001948/// CompareDerivedToBaseConversions - Compares two standard conversion
1949/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001950/// various kinds of derived-to-base conversions (C++
1951/// [over.ics.rank]p4b3). As part of these checks, we also look at
1952/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001953ImplicitConversionSequence::CompareKind
1954Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1955 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00001956 QualType FromType1 = SCS1.getFromType();
1957 QualType ToType1 = SCS1.getToType();
1958 QualType FromType2 = SCS2.getFromType();
1959 QualType ToType2 = SCS2.getToType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001960
1961 // Adjust the types we're converting from via the array-to-pointer
1962 // conversion, if we need to.
1963 if (SCS1.First == ICK_Array_To_Pointer)
1964 FromType1 = Context.getArrayDecayedType(FromType1);
1965 if (SCS2.First == ICK_Array_To_Pointer)
1966 FromType2 = Context.getArrayDecayedType(FromType2);
1967
1968 // Canonicalize all of the types.
1969 FromType1 = Context.getCanonicalType(FromType1);
1970 ToType1 = Context.getCanonicalType(ToType1);
1971 FromType2 = Context.getCanonicalType(FromType2);
1972 ToType2 = Context.getCanonicalType(ToType2);
1973
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001974 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001975 //
1976 // If class B is derived directly or indirectly from class A and
1977 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001978 //
1979 // For Objective-C, we let A, B, and C also be Objective-C
1980 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001981
1982 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00001983 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00001984 SCS2.Second == ICK_Pointer_Conversion &&
1985 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1986 FromType1->isPointerType() && FromType2->isPointerType() &&
1987 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001988 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001989 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001990 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001991 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001992 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001993 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001994 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001995 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001996
John McCall9dd450b2009-09-21 23:43:11 +00001997 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1998 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1999 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2000 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002001
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002002 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002003 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2004 if (IsDerivedFrom(ToPointee1, ToPointee2))
2005 return ImplicitConversionSequence::Better;
2006 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2007 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002008
2009 if (ToIface1 && ToIface2) {
2010 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2011 return ImplicitConversionSequence::Better;
2012 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2013 return ImplicitConversionSequence::Worse;
2014 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002015 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002016
2017 // -- conversion of B* to A* is better than conversion of C* to A*,
2018 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2019 if (IsDerivedFrom(FromPointee2, FromPointee1))
2020 return ImplicitConversionSequence::Better;
2021 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2022 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002023
Douglas Gregor237f96c2008-11-26 23:31:11 +00002024 if (FromIface1 && FromIface2) {
2025 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2026 return ImplicitConversionSequence::Better;
2027 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2028 return ImplicitConversionSequence::Worse;
2029 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002030 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002031 }
2032
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002033 // Compare based on reference bindings.
2034 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
2035 SCS1.Second == ICK_Derived_To_Base) {
2036 // -- binding of an expression of type C to a reference of type
2037 // B& is better than binding an expression of type C to a
2038 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002039 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2040 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002041 if (IsDerivedFrom(ToType1, ToType2))
2042 return ImplicitConversionSequence::Better;
2043 else if (IsDerivedFrom(ToType2, ToType1))
2044 return ImplicitConversionSequence::Worse;
2045 }
2046
Douglas Gregor2fe98832008-11-03 19:09:14 +00002047 // -- binding of an expression of type B to a reference of type
2048 // A& is better than binding an expression of type C to a
2049 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002050 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2051 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002052 if (IsDerivedFrom(FromType2, FromType1))
2053 return ImplicitConversionSequence::Better;
2054 else if (IsDerivedFrom(FromType1, FromType2))
2055 return ImplicitConversionSequence::Worse;
2056 }
2057 }
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002058
2059 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002060 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2061 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2062 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2063 const MemberPointerType * FromMemPointer1 =
2064 FromType1->getAs<MemberPointerType>();
2065 const MemberPointerType * ToMemPointer1 =
2066 ToType1->getAs<MemberPointerType>();
2067 const MemberPointerType * FromMemPointer2 =
2068 FromType2->getAs<MemberPointerType>();
2069 const MemberPointerType * ToMemPointer2 =
2070 ToType2->getAs<MemberPointerType>();
2071 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2072 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2073 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2074 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2075 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2076 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2077 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2078 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002079 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002080 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2081 if (IsDerivedFrom(ToPointee1, ToPointee2))
2082 return ImplicitConversionSequence::Worse;
2083 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2084 return ImplicitConversionSequence::Better;
2085 }
2086 // conversion of B::* to C::* is better than conversion of A::* to C::*
2087 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2088 if (IsDerivedFrom(FromPointee1, FromPointee2))
2089 return ImplicitConversionSequence::Better;
2090 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2091 return ImplicitConversionSequence::Worse;
2092 }
2093 }
2094
Douglas Gregor2fe98832008-11-03 19:09:14 +00002095 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
2096 SCS1.Second == ICK_Derived_To_Base) {
2097 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002098 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2099 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002100 if (IsDerivedFrom(ToType1, ToType2))
2101 return ImplicitConversionSequence::Better;
2102 else if (IsDerivedFrom(ToType2, ToType1))
2103 return ImplicitConversionSequence::Worse;
2104 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002105
Douglas Gregor2fe98832008-11-03 19:09:14 +00002106 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002107 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2108 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002109 if (IsDerivedFrom(FromType2, FromType1))
2110 return ImplicitConversionSequence::Better;
2111 else if (IsDerivedFrom(FromType1, FromType2))
2112 return ImplicitConversionSequence::Worse;
2113 }
2114 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002115
Douglas Gregor5c407d92008-10-23 00:40:37 +00002116 return ImplicitConversionSequence::Indistinguishable;
2117}
2118
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002119/// TryCopyInitialization - Try to copy-initialize a value of type
2120/// ToType from the expression From. Return the implicit conversion
2121/// sequence required to pass this argument, which may be a bad
2122/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002123/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00002124/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2125/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00002126ImplicitConversionSequence
2127Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002128 bool SuppressUserConversions, bool ForceRValue,
2129 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002130 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002131 ImplicitConversionSequence ICS;
Mike Stump11289f42009-09-09 15:08:12 +00002132 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002133 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002134 SuppressUserConversions,
2135 /*AllowExplicit=*/false,
2136 ForceRValue,
2137 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002138 return ICS;
2139 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002140 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002141 SuppressUserConversions,
2142 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002143 ForceRValue,
2144 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002145 }
2146}
2147
Sebastian Redl42e92c42009-04-12 17:16:29 +00002148/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2149/// the expression @p From. Returns true (and emits a diagnostic) if there was
2150/// an error, returns false if the initialization succeeded. Elidable should
2151/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2152/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002153bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002154 AssignmentAction Action, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002155 if (!getLangOptions().CPlusPlus) {
2156 // In C, argument passing is the same as performing an assignment.
2157 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002158
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002159 AssignConvertType ConvTy =
2160 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002161 if (ConvTy != Compatible &&
2162 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2163 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002164
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002165 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002166 FromType, From, Action);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002167 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002168
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002169 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002170 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002171 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002172 /*SuppressUserConversions=*/false,
2173 /*AllowExplicit=*/false,
2174 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002175
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002176 if (!PerformImplicitConversion(From, ToType, Action,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002177 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002178 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00002179 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002180 return Diag(From->getSourceRange().getBegin(),
2181 diag::err_typecheck_convert_incompatible)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002182 << ToType << From->getType() << Action << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002183 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002184}
2185
Douglas Gregor436424c2008-11-18 23:14:02 +00002186/// TryObjectArgumentInitialization - Try to initialize the object
2187/// parameter of the given member function (@c Method) from the
2188/// expression @p From.
2189ImplicitConversionSequence
John McCall6e9f8f62009-12-03 04:06:58 +00002190Sema::TryObjectArgumentInitialization(QualType FromType,
2191 CXXMethodDecl *Method,
2192 CXXRecordDecl *ActingContext) {
2193 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002194 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2195 // const volatile object.
2196 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2197 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2198 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002199
2200 // Set up the conversion sequence as a "bad" conversion, to allow us
2201 // to exit early.
2202 ImplicitConversionSequence ICS;
2203 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00002204 ICS.setBad();
Douglas Gregor436424c2008-11-18 23:14:02 +00002205
2206 // We need to have an object of class type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002207 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002208 FromType = PT->getPointeeType();
2209
2210 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002211
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002212 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002213 // where X is the class of which the function is a member
2214 // (C++ [over.match.funcs]p4). However, when finding an implicit
2215 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002216 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002217 // (C++ [over.match.funcs]p5). We perform a simplified version of
2218 // reference binding here, that allows class rvalues to bind to
2219 // non-constant references.
2220
2221 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2222 // with the implicit object parameter (C++ [over.match.funcs]p5).
2223 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002224 if (ImplicitParamType.getCVRQualifiers()
2225 != FromTypeCanon.getLocalCVRQualifiers() &&
Douglas Gregor01df9462009-11-05 00:07:36 +00002226 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon))
Douglas Gregor436424c2008-11-18 23:14:02 +00002227 return ICS;
2228
2229 // Check that we have either the same type or a derived type. It
2230 // affects the conversion rank.
2231 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002232 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor436424c2008-11-18 23:14:02 +00002233 ICS.Standard.Second = ICK_Identity;
2234 else if (IsDerivedFrom(FromType, ClassType))
2235 ICS.Standard.Second = ICK_Derived_To_Base;
2236 else
2237 return ICS;
2238
2239 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002240 ICS.setStandard();
2241 ICS.Standard.setFromType(FromType);
2242 ICS.Standard.setToType(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002243 ICS.Standard.ReferenceBinding = true;
2244 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002245 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002246 return ICS;
2247}
2248
2249/// PerformObjectArgumentInitialization - Perform initialization of
2250/// the implicit object parameter for the given Method with the given
2251/// expression.
2252bool
2253Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002254 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002255 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002256 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002257
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002258 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002259 FromRecordType = PT->getPointeeType();
2260 DestType = Method->getThisType(Context);
2261 } else {
2262 FromRecordType = From->getType();
2263 DestType = ImplicitParamRecordType;
2264 }
2265
John McCall6e9f8f62009-12-03 04:06:58 +00002266 // Note that we always use the true parent context when performing
2267 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002268 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002269 = TryObjectArgumentInitialization(From->getType(), Method,
2270 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002271 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002272 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002273 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002274 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002275
Douglas Gregor436424c2008-11-18 23:14:02 +00002276 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002277 CheckDerivedToBaseConversion(FromRecordType,
2278 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002279 From->getSourceRange().getBegin(),
2280 From->getSourceRange()))
2281 return true;
2282
Mike Stump11289f42009-09-09 15:08:12 +00002283 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002284 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002285 return false;
2286}
2287
Douglas Gregor5fb53972009-01-14 15:45:31 +00002288/// TryContextuallyConvertToBool - Attempt to contextually convert the
2289/// expression From to bool (C++0x [conv]p3).
2290ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002291 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002292 // FIXME: Are these flags correct?
2293 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002294 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002295 /*ForceRValue=*/false,
2296 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002297}
2298
2299/// PerformContextuallyConvertToBool - Perform a contextual conversion
2300/// of the expression From to bool (C++0x [conv]p3).
2301bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2302 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00002303 if (!ICS.isBad())
2304 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002305
Fariborz Jahanian76197412009-11-18 18:26:29 +00002306 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002307 return Diag(From->getSourceRange().getBegin(),
2308 diag::err_typecheck_bool_condition)
2309 << From->getType() << From->getSourceRange();
2310 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002311}
2312
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002313/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002314/// candidate functions, using the given function call arguments. If
2315/// @p SuppressUserConversions, then don't allow user-defined
2316/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002317/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2318/// hacky way to implement the overloading rules for elidable copy
2319/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002320///
2321/// \para PartialOverloading true if we are performing "partial" overloading
2322/// based on an incomplete set of function arguments. This feature is used by
2323/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002324void
2325Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002326 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002327 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002328 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002329 bool ForceRValue,
2330 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002331 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002332 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002333 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002334 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002335 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002336
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002337 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002338 if (!isa<CXXConstructorDecl>(Method)) {
2339 // If we get here, it's because we're calling a member function
2340 // that is named without a member access expression (e.g.,
2341 // "this->f") that was either written explicitly or created
2342 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002343 // function, e.g., X::f(). We use an empty type for the implied
2344 // object argument (C++ [over.call.func]p3), and the acting context
2345 // is irrelevant.
2346 AddMethodCandidate(Method, Method->getParent(),
2347 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002348 SuppressUserConversions, ForceRValue);
2349 return;
2350 }
2351 // We treat a constructor like a non-member function, since its object
2352 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002353 }
2354
Douglas Gregorff7028a2009-11-13 23:59:09 +00002355 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002356 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002357
Douglas Gregor27381f32009-11-23 12:27:39 +00002358 // Overload resolution is always an unevaluated context.
2359 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2360
Douglas Gregorffe14e32009-11-14 01:20:54 +00002361 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2362 // C++ [class.copy]p3:
2363 // A member function template is never instantiated to perform the copy
2364 // of a class object to an object of its class type.
2365 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2366 if (NumArgs == 1 &&
2367 Constructor->isCopyConstructorLikeSpecialization() &&
2368 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2369 return;
2370 }
2371
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002372 // Add this candidate
2373 CandidateSet.push_back(OverloadCandidate());
2374 OverloadCandidate& Candidate = CandidateSet.back();
2375 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002376 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002377 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002378 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002379
2380 unsigned NumArgsInProto = Proto->getNumArgs();
2381
2382 // (C++ 13.3.2p2): A candidate function having fewer than m
2383 // parameters is viable only if it has an ellipsis in its parameter
2384 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002385 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2386 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002387 Candidate.Viable = false;
2388 return;
2389 }
2390
2391 // (C++ 13.3.2p2): A candidate function having more than m parameters
2392 // is viable only if the (m+1)st parameter has a default argument
2393 // (8.3.6). For the purposes of overload resolution, the
2394 // parameter list is truncated on the right, so that there are
2395 // exactly m parameters.
2396 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002397 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002398 // Not enough arguments.
2399 Candidate.Viable = false;
2400 return;
2401 }
2402
2403 // Determine the implicit conversion sequences for each of the
2404 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002405 Candidate.Conversions.resize(NumArgs);
2406 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2407 if (ArgIdx < NumArgsInProto) {
2408 // (C++ 13.3.2p3): for F to be a viable function, there shall
2409 // exist for each argument an implicit conversion sequence
2410 // (13.3.3.1) that converts that argument to the corresponding
2411 // parameter of F.
2412 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002413 Candidate.Conversions[ArgIdx]
2414 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002415 SuppressUserConversions, ForceRValue,
2416 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002417 if (Candidate.Conversions[ArgIdx].isBad()) {
2418 Candidate.Viable = false;
2419 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00002420 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002421 } else {
2422 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2423 // argument for which there is no corresponding parameter is
2424 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002425 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002426 }
2427 }
2428}
2429
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002430/// \brief Add all of the function declarations in the given function set to
2431/// the overload canddiate set.
2432void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2433 Expr **Args, unsigned NumArgs,
2434 OverloadCandidateSet& CandidateSet,
2435 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002436 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002437 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002438 F != FEnd; ++F) {
John McCall6e9f8f62009-12-03 04:06:58 +00002439 // FIXME: using declarations
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002440 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2441 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2442 AddMethodCandidate(cast<CXXMethodDecl>(FD),
John McCall6e9f8f62009-12-03 04:06:58 +00002443 cast<CXXMethodDecl>(FD)->getParent(),
2444 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002445 CandidateSet, SuppressUserConversions);
2446 else
2447 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2448 SuppressUserConversions);
2449 } else {
2450 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2451 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2452 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2453 AddMethodTemplateCandidate(FunTmpl,
John McCall6e9f8f62009-12-03 04:06:58 +00002454 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002455 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002456 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002457 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002458 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002459 else
2460 AddTemplateOverloadCandidate(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00002461 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002462 Args, NumArgs, CandidateSet,
2463 SuppressUserConversions);
2464 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002465 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002466}
2467
John McCallf0f1cf02009-11-17 07:50:12 +00002468/// AddMethodCandidate - Adds a named decl (which is some kind of
2469/// method) as a method candidate to the given overload set.
John McCall6e9f8f62009-12-03 04:06:58 +00002470void Sema::AddMethodCandidate(NamedDecl *Decl,
2471 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002472 Expr **Args, unsigned NumArgs,
2473 OverloadCandidateSet& CandidateSet,
2474 bool SuppressUserConversions, bool ForceRValue) {
John McCall6e9f8f62009-12-03 04:06:58 +00002475 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002476
2477 if (isa<UsingShadowDecl>(Decl))
2478 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2479
2480 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2481 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2482 "Expected a member function template");
John McCall6e9f8f62009-12-03 04:06:58 +00002483 AddMethodTemplateCandidate(TD, ActingContext, /*ExplicitArgs*/ 0,
2484 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002485 CandidateSet,
2486 SuppressUserConversions,
2487 ForceRValue);
2488 } else {
John McCall6e9f8f62009-12-03 04:06:58 +00002489 AddMethodCandidate(cast<CXXMethodDecl>(Decl), ActingContext,
2490 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002491 CandidateSet, SuppressUserConversions, ForceRValue);
2492 }
2493}
2494
Douglas Gregor436424c2008-11-18 23:14:02 +00002495/// AddMethodCandidate - Adds the given C++ member function to the set
2496/// of candidate functions, using the given function call arguments
2497/// and the object argument (@c Object). For example, in a call
2498/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2499/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2500/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002501/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2502/// a slightly hacky way to implement the overloading rules for elidable copy
2503/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002504void
John McCall6e9f8f62009-12-03 04:06:58 +00002505Sema::AddMethodCandidate(CXXMethodDecl *Method, CXXRecordDecl *ActingContext,
2506 QualType ObjectType, Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002507 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002508 bool SuppressUserConversions, bool ForceRValue) {
2509 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002510 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002511 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002512 assert(!isa<CXXConstructorDecl>(Method) &&
2513 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002514
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002515 if (!CandidateSet.isNewCandidate(Method))
2516 return;
2517
Douglas Gregor27381f32009-11-23 12:27:39 +00002518 // Overload resolution is always an unevaluated context.
2519 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2520
Douglas Gregor436424c2008-11-18 23:14:02 +00002521 // Add this candidate
2522 CandidateSet.push_back(OverloadCandidate());
2523 OverloadCandidate& Candidate = CandidateSet.back();
2524 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002525 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002526 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002527
2528 unsigned NumArgsInProto = Proto->getNumArgs();
2529
2530 // (C++ 13.3.2p2): A candidate function having fewer than m
2531 // parameters is viable only if it has an ellipsis in its parameter
2532 // list (8.3.5).
2533 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2534 Candidate.Viable = false;
2535 return;
2536 }
2537
2538 // (C++ 13.3.2p2): A candidate function having more than m parameters
2539 // is viable only if the (m+1)st parameter has a default argument
2540 // (8.3.6). For the purposes of overload resolution, the
2541 // parameter list is truncated on the right, so that there are
2542 // exactly m parameters.
2543 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2544 if (NumArgs < MinRequiredArgs) {
2545 // Not enough arguments.
2546 Candidate.Viable = false;
2547 return;
2548 }
2549
2550 Candidate.Viable = true;
2551 Candidate.Conversions.resize(NumArgs + 1);
2552
John McCall6e9f8f62009-12-03 04:06:58 +00002553 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002554 // The implicit object argument is ignored.
2555 Candidate.IgnoreObjectArgument = true;
2556 else {
2557 // Determine the implicit conversion sequence for the object
2558 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002559 Candidate.Conversions[0]
2560 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002561 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002562 Candidate.Viable = false;
2563 return;
2564 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002565 }
2566
2567 // Determine the implicit conversion sequences for each of the
2568 // arguments.
2569 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2570 if (ArgIdx < NumArgsInProto) {
2571 // (C++ 13.3.2p3): for F to be a viable function, there shall
2572 // exist for each argument an implicit conversion sequence
2573 // (13.3.3.1) that converts that argument to the corresponding
2574 // parameter of F.
2575 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002576 Candidate.Conversions[ArgIdx + 1]
2577 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002578 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002579 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002580 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002581 Candidate.Viable = false;
2582 break;
2583 }
2584 } else {
2585 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2586 // argument for which there is no corresponding parameter is
2587 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002588 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00002589 }
2590 }
2591}
2592
Douglas Gregor97628d62009-08-21 00:16:32 +00002593/// \brief Add a C++ member function template as a candidate to the candidate
2594/// set, using template argument deduction to produce an appropriate member
2595/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002596void
Douglas Gregor97628d62009-08-21 00:16:32 +00002597Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall6e9f8f62009-12-03 04:06:58 +00002598 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00002599 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00002600 QualType ObjectType,
2601 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002602 OverloadCandidateSet& CandidateSet,
2603 bool SuppressUserConversions,
2604 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002605 if (!CandidateSet.isNewCandidate(MethodTmpl))
2606 return;
2607
Douglas Gregor97628d62009-08-21 00:16:32 +00002608 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002609 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002610 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002611 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002612 // candidate functions in the usual way.113) A given name can refer to one
2613 // or more function templates and also to a set of overloaded non-template
2614 // functions. In such a case, the candidate functions generated from each
2615 // function template are combined with the set of non-template candidate
2616 // functions.
2617 TemplateDeductionInfo Info(Context);
2618 FunctionDecl *Specialization = 0;
2619 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002620 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002621 Args, NumArgs, Specialization, Info)) {
2622 // FIXME: Record what happened with template argument deduction, so
2623 // that we can give the user a beautiful diagnostic.
2624 (void)Result;
2625 return;
2626 }
Mike Stump11289f42009-09-09 15:08:12 +00002627
Douglas Gregor97628d62009-08-21 00:16:32 +00002628 // Add the function template specialization produced by template argument
2629 // deduction as a candidate.
2630 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002631 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002632 "Specialization is not a member function?");
John McCall6e9f8f62009-12-03 04:06:58 +00002633 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), ActingContext,
2634 ObjectType, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002635 CandidateSet, SuppressUserConversions, ForceRValue);
2636}
2637
Douglas Gregor05155d82009-08-21 23:19:43 +00002638/// \brief Add a C++ function template specialization as a candidate
2639/// in the candidate set, using template argument deduction to produce
2640/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002641void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002642Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00002643 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002644 Expr **Args, unsigned NumArgs,
2645 OverloadCandidateSet& CandidateSet,
2646 bool SuppressUserConversions,
2647 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002648 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2649 return;
2650
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002651 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002652 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002653 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002654 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002655 // candidate functions in the usual way.113) A given name can refer to one
2656 // or more function templates and also to a set of overloaded non-template
2657 // functions. In such a case, the candidate functions generated from each
2658 // function template are combined with the set of non-template candidate
2659 // functions.
2660 TemplateDeductionInfo Info(Context);
2661 FunctionDecl *Specialization = 0;
2662 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002663 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002664 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002665 // FIXME: Record what happened with template argument deduction, so
2666 // that we can give the user a beautiful diagnostic.
John McCalld681c392009-12-16 08:11:27 +00002667 (void) Result;
2668
2669 CandidateSet.push_back(OverloadCandidate());
2670 OverloadCandidate &Candidate = CandidateSet.back();
2671 Candidate.Function = FunctionTemplate->getTemplatedDecl();
2672 Candidate.Viable = false;
2673 Candidate.IsSurrogate = false;
2674 Candidate.IgnoreObjectArgument = false;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002675 return;
2676 }
Mike Stump11289f42009-09-09 15:08:12 +00002677
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002678 // Add the function template specialization produced by template argument
2679 // deduction as a candidate.
2680 assert(Specialization && "Missing function template specialization?");
2681 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2682 SuppressUserConversions, ForceRValue);
2683}
Mike Stump11289f42009-09-09 15:08:12 +00002684
Douglas Gregora1f013e2008-11-07 22:36:19 +00002685/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002686/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002687/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002688/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002689/// (which may or may not be the same type as the type that the
2690/// conversion function produces).
2691void
2692Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall6e9f8f62009-12-03 04:06:58 +00002693 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002694 Expr *From, QualType ToType,
2695 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002696 assert(!Conversion->getDescribedFunctionTemplate() &&
2697 "Conversion function templates use AddTemplateConversionCandidate");
2698
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002699 if (!CandidateSet.isNewCandidate(Conversion))
2700 return;
2701
Douglas Gregor27381f32009-11-23 12:27:39 +00002702 // Overload resolution is always an unevaluated context.
2703 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2704
Douglas Gregora1f013e2008-11-07 22:36:19 +00002705 // Add this candidate
2706 CandidateSet.push_back(OverloadCandidate());
2707 OverloadCandidate& Candidate = CandidateSet.back();
2708 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002709 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002710 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002711 Candidate.FinalConversion.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00002712 Candidate.FinalConversion.setFromType(Conversion->getConversionType());
2713 Candidate.FinalConversion.setToType(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00002714
Douglas Gregor436424c2008-11-18 23:14:02 +00002715 // Determine the implicit conversion sequence for the implicit
2716 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002717 Candidate.Viable = true;
2718 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00002719 Candidate.Conversions[0]
2720 = TryObjectArgumentInitialization(From->getType(), Conversion,
2721 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002722 // Conversion functions to a different type in the base class is visible in
2723 // the derived class. So, a derived to base conversion should not participate
2724 // in overload resolution.
2725 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2726 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00002727 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002728 Candidate.Viable = false;
2729 return;
2730 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002731
2732 // We won't go through a user-define type conversion function to convert a
2733 // derived to base as such conversions are given Conversion Rank. They only
2734 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2735 QualType FromCanon
2736 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2737 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2738 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2739 Candidate.Viable = false;
2740 return;
2741 }
2742
Douglas Gregora1f013e2008-11-07 22:36:19 +00002743
2744 // To determine what the conversion from the result of calling the
2745 // conversion function to the type we're eventually trying to
2746 // convert to (ToType), we need to synthesize a call to the
2747 // conversion function and attempt copy initialization from it. This
2748 // makes sure that we get the right semantics with respect to
2749 // lvalues/rvalues and the type. Fortunately, we can allocate this
2750 // call on the stack and we don't need its arguments to be
2751 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002752 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002753 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00002754 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002755 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002756 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002757
2758 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002759 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2760 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002761 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002762 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002763 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002764 ImplicitConversionSequence ICS =
2765 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002766 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002767 /*ForceRValue=*/false,
2768 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002769
John McCall0d1da222010-01-12 00:44:57 +00002770 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002771 case ImplicitConversionSequence::StandardConversion:
2772 Candidate.FinalConversion = ICS.Standard;
2773 break;
2774
2775 case ImplicitConversionSequence::BadConversion:
2776 Candidate.Viable = false;
2777 break;
2778
2779 default:
Mike Stump11289f42009-09-09 15:08:12 +00002780 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002781 "Can only end up with a standard conversion sequence or failure");
2782 }
2783}
2784
Douglas Gregor05155d82009-08-21 23:19:43 +00002785/// \brief Adds a conversion function template specialization
2786/// candidate to the overload set, using template argument deduction
2787/// to deduce the template arguments of the conversion function
2788/// template from the type that we are converting to (C++
2789/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002790void
Douglas Gregor05155d82009-08-21 23:19:43 +00002791Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6e9f8f62009-12-03 04:06:58 +00002792 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00002793 Expr *From, QualType ToType,
2794 OverloadCandidateSet &CandidateSet) {
2795 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2796 "Only conversion function templates permitted here");
2797
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002798 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2799 return;
2800
Douglas Gregor05155d82009-08-21 23:19:43 +00002801 TemplateDeductionInfo Info(Context);
2802 CXXConversionDecl *Specialization = 0;
2803 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002804 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002805 Specialization, Info)) {
2806 // FIXME: Record what happened with template argument deduction, so
2807 // that we can give the user a beautiful diagnostic.
2808 (void)Result;
2809 return;
2810 }
Mike Stump11289f42009-09-09 15:08:12 +00002811
Douglas Gregor05155d82009-08-21 23:19:43 +00002812 // Add the conversion function template specialization produced by
2813 // template argument deduction as a candidate.
2814 assert(Specialization && "Missing function template specialization?");
John McCall6e9f8f62009-12-03 04:06:58 +00002815 AddConversionCandidate(Specialization, ActingDC, From, ToType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00002816}
2817
Douglas Gregorab7897a2008-11-19 22:57:39 +00002818/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2819/// converts the given @c Object to a function pointer via the
2820/// conversion function @c Conversion, and then attempts to call it
2821/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2822/// the type of function that we'll eventually be calling.
2823void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall6e9f8f62009-12-03 04:06:58 +00002824 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002825 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00002826 QualType ObjectType,
2827 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002828 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002829 if (!CandidateSet.isNewCandidate(Conversion))
2830 return;
2831
Douglas Gregor27381f32009-11-23 12:27:39 +00002832 // Overload resolution is always an unevaluated context.
2833 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2834
Douglas Gregorab7897a2008-11-19 22:57:39 +00002835 CandidateSet.push_back(OverloadCandidate());
2836 OverloadCandidate& Candidate = CandidateSet.back();
2837 Candidate.Function = 0;
2838 Candidate.Surrogate = Conversion;
2839 Candidate.Viable = true;
2840 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002841 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002842 Candidate.Conversions.resize(NumArgs + 1);
2843
2844 // Determine the implicit conversion sequence for the implicit
2845 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002846 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00002847 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002848 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00002849 Candidate.Viable = false;
2850 return;
2851 }
2852
2853 // The first conversion is actually a user-defined conversion whose
2854 // first conversion is ObjectInit's standard conversion (which is
2855 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00002856 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00002857 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002858 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002859 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002860 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002861 = Candidate.Conversions[0].UserDefined.Before;
2862 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2863
Mike Stump11289f42009-09-09 15:08:12 +00002864 // Find the
Douglas Gregorab7897a2008-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 Stump11289f42009-09-09 15:08:12 +00002892 Candidate.Conversions[ArgIdx + 1]
2893 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002894 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002895 /*ForceRValue=*/false,
2896 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00002897 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00002898 Candidate.Viable = false;
2899 break;
2900 }
2901 } else {
2902 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2903 // argument for which there is no corresponding parameter is
2904 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002905 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00002906 }
2907 }
2908}
2909
Mike Stump87c57ac2009-05-16 07:39:55 +00002910// FIXME: This will eventually be removed, once we've migrated all of the
2911// operator overloading logic over to the scheme used by binary operators, which
2912// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002913void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002914 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002915 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002916 OverloadCandidateSet& CandidateSet,
2917 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002918 FunctionSet Functions;
2919
2920 QualType T1 = Args[0]->getType();
2921 QualType T2;
2922 if (NumArgs > 1)
2923 T2 = Args[1]->getType();
2924
2925 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002926 if (S)
2927 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redlc057f422009-10-23 19:23:15 +00002928 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002929 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2930 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002931 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002932}
2933
2934/// \brief Add overload candidates for overloaded operators that are
2935/// member functions.
2936///
2937/// Add the overloaded operator candidates that are member functions
2938/// for the operator Op that was used in an operator expression such
2939/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2940/// CandidateSet will store the added overload candidates. (C++
2941/// [over.match.oper]).
2942void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2943 SourceLocation OpLoc,
2944 Expr **Args, unsigned NumArgs,
2945 OverloadCandidateSet& CandidateSet,
2946 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002947 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2948
2949 // C++ [over.match.oper]p3:
2950 // For a unary operator @ with an operand of a type whose
2951 // cv-unqualified version is T1, and for a binary operator @ with
2952 // a left operand of a type whose cv-unqualified version is T1 and
2953 // a right operand of a type whose cv-unqualified version is T2,
2954 // three sets of candidate functions, designated member
2955 // candidates, non-member candidates and built-in candidates, are
2956 // constructed as follows:
2957 QualType T1 = Args[0]->getType();
2958 QualType T2;
2959 if (NumArgs > 1)
2960 T2 = Args[1]->getType();
2961
2962 // -- If T1 is a class type, the set of member candidates is the
2963 // result of the qualified lookup of T1::operator@
2964 // (13.3.1.1.1); otherwise, the set of member candidates is
2965 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002966 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002967 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00002968 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002969 return;
Mike Stump11289f42009-09-09 15:08:12 +00002970
John McCall27b18f82009-11-17 02:14:36 +00002971 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
2972 LookupQualifiedName(Operators, T1Rec->getDecl());
2973 Operators.suppressDiagnostics();
2974
Mike Stump11289f42009-09-09 15:08:12 +00002975 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002976 OperEnd = Operators.end();
2977 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00002978 ++Oper)
John McCall6e9f8f62009-12-03 04:06:58 +00002979 AddMethodCandidate(*Oper, Args[0]->getType(),
2980 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00002981 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00002982 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002983}
2984
Douglas Gregora11693b2008-11-12 17:17:38 +00002985/// AddBuiltinCandidate - Add a candidate for a built-in
2986/// operator. ResultTy and ParamTys are the result and parameter types
2987/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00002988/// arguments being passed to the candidate. IsAssignmentOperator
2989/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00002990/// operator. NumContextualBoolArguments is the number of arguments
2991/// (at the beginning of the argument list) that will be contextually
2992/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00002993void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00002994 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00002995 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002996 bool IsAssignmentOperator,
2997 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00002998 // Overload resolution is always an unevaluated context.
2999 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3000
Douglas Gregora11693b2008-11-12 17:17:38 +00003001 // Add this candidate
3002 CandidateSet.push_back(OverloadCandidate());
3003 OverloadCandidate& Candidate = CandidateSet.back();
3004 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003005 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003006 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003007 Candidate.BuiltinTypes.ResultTy = ResultTy;
3008 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3009 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3010
3011 // Determine the implicit conversion sequences for each of the
3012 // arguments.
3013 Candidate.Viable = true;
3014 Candidate.Conversions.resize(NumArgs);
3015 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003016 // C++ [over.match.oper]p4:
3017 // For the built-in assignment operators, conversions of the
3018 // left operand are restricted as follows:
3019 // -- no temporaries are introduced to hold the left operand, and
3020 // -- no user-defined conversions are applied to the left
3021 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003022 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003023 //
3024 // We block these conversions by turning off user-defined
3025 // conversions, since that is the only way that initialization of
3026 // a reference to a non-class type can occur from something that
3027 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003028 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003029 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003030 "Contextual conversion to bool requires bool type");
3031 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3032 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003033 Candidate.Conversions[ArgIdx]
3034 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003035 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003036 /*ForceRValue=*/false,
3037 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003038 }
John McCall0d1da222010-01-12 00:44:57 +00003039 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003040 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003041 break;
3042 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003043 }
3044}
3045
3046/// BuiltinCandidateTypeSet - A set of types that will be used for the
3047/// candidate operator functions for built-in operators (C++
3048/// [over.built]). The types are separated into pointer types and
3049/// enumeration types.
3050class BuiltinCandidateTypeSet {
3051 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003052 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003053
3054 /// PointerTypes - The set of pointer types that will be used in the
3055 /// built-in candidates.
3056 TypeSet PointerTypes;
3057
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003058 /// MemberPointerTypes - The set of member pointer types that will be
3059 /// used in the built-in candidates.
3060 TypeSet MemberPointerTypes;
3061
Douglas Gregora11693b2008-11-12 17:17:38 +00003062 /// EnumerationTypes - The set of enumeration types that will be
3063 /// used in the built-in candidates.
3064 TypeSet EnumerationTypes;
3065
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003066 /// Sema - The semantic analysis instance where we are building the
3067 /// candidate type set.
3068 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003069
Douglas Gregora11693b2008-11-12 17:17:38 +00003070 /// Context - The AST context in which we will build the type sets.
3071 ASTContext &Context;
3072
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003073 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3074 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003075 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003076
3077public:
3078 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003079 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003080
Mike Stump11289f42009-09-09 15:08:12 +00003081 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003082 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003083
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003084 void AddTypesConvertedFrom(QualType Ty,
3085 SourceLocation Loc,
3086 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003087 bool AllowExplicitConversions,
3088 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003089
3090 /// pointer_begin - First pointer type found;
3091 iterator pointer_begin() { return PointerTypes.begin(); }
3092
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003093 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003094 iterator pointer_end() { return PointerTypes.end(); }
3095
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003096 /// member_pointer_begin - First member pointer type found;
3097 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3098
3099 /// member_pointer_end - Past the last member pointer type found;
3100 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3101
Douglas Gregora11693b2008-11-12 17:17:38 +00003102 /// enumeration_begin - First enumeration type found;
3103 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3104
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003105 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003106 iterator enumeration_end() { return EnumerationTypes.end(); }
3107};
3108
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003109/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003110/// the set of pointer types along with any more-qualified variants of
3111/// that type. For example, if @p Ty is "int const *", this routine
3112/// will add "int const *", "int const volatile *", "int const
3113/// restrict *", and "int const volatile restrict *" to the set of
3114/// pointer types. Returns true if the add of @p Ty itself succeeded,
3115/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003116///
3117/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003118bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003119BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3120 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003121
Douglas Gregora11693b2008-11-12 17:17:38 +00003122 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003123 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003124 return false;
3125
John McCall8ccfcb52009-09-24 19:53:00 +00003126 const PointerType *PointerTy = Ty->getAs<PointerType>();
3127 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003128
John McCall8ccfcb52009-09-24 19:53:00 +00003129 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003130 // Don't add qualified variants of arrays. For one, they're not allowed
3131 // (the qualifier would sink to the element type), and for another, the
3132 // only overload situation where it matters is subscript or pointer +- int,
3133 // and those shouldn't have qualifier variants anyway.
3134 if (PointeeTy->isArrayType())
3135 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003136 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003137 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003138 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003139 bool hasVolatile = VisibleQuals.hasVolatile();
3140 bool hasRestrict = VisibleQuals.hasRestrict();
3141
John McCall8ccfcb52009-09-24 19:53:00 +00003142 // Iterate through all strict supersets of BaseCVR.
3143 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3144 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003145 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3146 // in the types.
3147 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3148 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003149 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3150 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003151 }
3152
3153 return true;
3154}
3155
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003156/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3157/// to the set of pointer types along with any more-qualified variants of
3158/// that type. For example, if @p Ty is "int const *", this routine
3159/// will add "int const *", "int const volatile *", "int const
3160/// restrict *", and "int const volatile restrict *" to the set of
3161/// pointer types. Returns true if the add of @p Ty itself succeeded,
3162/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003163///
3164/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003165bool
3166BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3167 QualType Ty) {
3168 // Insert this type.
3169 if (!MemberPointerTypes.insert(Ty))
3170 return false;
3171
John McCall8ccfcb52009-09-24 19:53:00 +00003172 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3173 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003174
John McCall8ccfcb52009-09-24 19:53:00 +00003175 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003176 // Don't add qualified variants of arrays. For one, they're not allowed
3177 // (the qualifier would sink to the element type), and for another, the
3178 // only overload situation where it matters is subscript or pointer +- int,
3179 // and those shouldn't have qualifier variants anyway.
3180 if (PointeeTy->isArrayType())
3181 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003182 const Type *ClassTy = PointerTy->getClass();
3183
3184 // Iterate through all strict supersets of the pointee type's CVR
3185 // qualifiers.
3186 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3187 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3188 if ((CVR | BaseCVR) != CVR) continue;
3189
3190 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3191 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003192 }
3193
3194 return true;
3195}
3196
Douglas Gregora11693b2008-11-12 17:17:38 +00003197/// AddTypesConvertedFrom - Add each of the types to which the type @p
3198/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003199/// primarily interested in pointer types and enumeration types. We also
3200/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003201/// AllowUserConversions is true if we should look at the conversion
3202/// functions of a class type, and AllowExplicitConversions if we
3203/// should also include the explicit conversion functions of a class
3204/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003205void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003206BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003207 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003208 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003209 bool AllowExplicitConversions,
3210 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003211 // Only deal with canonical types.
3212 Ty = Context.getCanonicalType(Ty);
3213
3214 // Look through reference types; they aren't part of the type of an
3215 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003216 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003217 Ty = RefTy->getPointeeType();
3218
3219 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003220 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003221
Sebastian Redl65ae2002009-11-05 16:36:20 +00003222 // If we're dealing with an array type, decay to the pointer.
3223 if (Ty->isArrayType())
3224 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3225
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003226 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003227 QualType PointeeTy = PointerTy->getPointeeType();
3228
3229 // Insert our type, and its more-qualified variants, into the set
3230 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003231 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003232 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003233 } else if (Ty->isMemberPointerType()) {
3234 // Member pointers are far easier, since the pointee can't be converted.
3235 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3236 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003237 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003238 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003239 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003240 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003241 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003242 // No conversion functions in incomplete types.
3243 return;
3244 }
Mike Stump11289f42009-09-09 15:08:12 +00003245
Douglas Gregora11693b2008-11-12 17:17:38 +00003246 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalld14a8642009-11-21 08:51:07 +00003247 const UnresolvedSet *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003248 = ClassDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00003249 for (UnresolvedSet::iterator I = Conversions->begin(),
3250 E = Conversions->end(); I != E; ++I) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003251
Mike Stump11289f42009-09-09 15:08:12 +00003252 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003253 // about which builtin types we can convert to.
John McCalld14a8642009-11-21 08:51:07 +00003254 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor05155d82009-08-21 23:19:43 +00003255 continue;
3256
John McCalld14a8642009-11-21 08:51:07 +00003257 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003258 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003259 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003260 VisibleQuals);
3261 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003262 }
3263 }
3264 }
3265}
3266
Douglas Gregor84605ae2009-08-24 13:43:27 +00003267/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3268/// the volatile- and non-volatile-qualified assignment operators for the
3269/// given type to the candidate set.
3270static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3271 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003272 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003273 unsigned NumArgs,
3274 OverloadCandidateSet &CandidateSet) {
3275 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003276
Douglas Gregor84605ae2009-08-24 13:43:27 +00003277 // T& operator=(T&, T)
3278 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3279 ParamTypes[1] = T;
3280 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3281 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003282
Douglas Gregor84605ae2009-08-24 13:43:27 +00003283 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3284 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003285 ParamTypes[0]
3286 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003287 ParamTypes[1] = T;
3288 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003289 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003290 }
3291}
Mike Stump11289f42009-09-09 15:08:12 +00003292
Sebastian Redl1054fae2009-10-25 17:03:50 +00003293/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3294/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003295static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3296 Qualifiers VRQuals;
3297 const RecordType *TyRec;
3298 if (const MemberPointerType *RHSMPType =
3299 ArgExpr->getType()->getAs<MemberPointerType>())
3300 TyRec = cast<RecordType>(RHSMPType->getClass());
3301 else
3302 TyRec = ArgExpr->getType()->getAs<RecordType>();
3303 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003304 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003305 VRQuals.addVolatile();
3306 VRQuals.addRestrict();
3307 return VRQuals;
3308 }
3309
3310 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalld14a8642009-11-21 08:51:07 +00003311 const UnresolvedSet *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003312 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003313
John McCalld14a8642009-11-21 08:51:07 +00003314 for (UnresolvedSet::iterator I = Conversions->begin(),
3315 E = Conversions->end(); I != E; ++I) {
3316 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003317 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3318 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3319 CanTy = ResTypeRef->getPointeeType();
3320 // Need to go down the pointer/mempointer chain and add qualifiers
3321 // as see them.
3322 bool done = false;
3323 while (!done) {
3324 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3325 CanTy = ResTypePtr->getPointeeType();
3326 else if (const MemberPointerType *ResTypeMPtr =
3327 CanTy->getAs<MemberPointerType>())
3328 CanTy = ResTypeMPtr->getPointeeType();
3329 else
3330 done = true;
3331 if (CanTy.isVolatileQualified())
3332 VRQuals.addVolatile();
3333 if (CanTy.isRestrictQualified())
3334 VRQuals.addRestrict();
3335 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3336 return VRQuals;
3337 }
3338 }
3339 }
3340 return VRQuals;
3341}
3342
Douglas Gregord08452f2008-11-19 15:42:04 +00003343/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3344/// operator overloads to the candidate set (C++ [over.built]), based
3345/// on the operator @p Op and the arguments given. For example, if the
3346/// operator is a binary '+', this routine might add "int
3347/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003348void
Mike Stump11289f42009-09-09 15:08:12 +00003349Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003350 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003351 Expr **Args, unsigned NumArgs,
3352 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003353 // The set of "promoted arithmetic types", which are the arithmetic
3354 // types are that preserved by promotion (C++ [over.built]p2). Note
3355 // that the first few of these types are the promoted integral
3356 // types; these types need to be first.
3357 // FIXME: What about complex?
3358 const unsigned FirstIntegralType = 0;
3359 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003360 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003361 LastPromotedIntegralType = 13;
3362 const unsigned FirstPromotedArithmeticType = 7,
3363 LastPromotedArithmeticType = 16;
3364 const unsigned NumArithmeticTypes = 16;
3365 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003366 Context.BoolTy, Context.CharTy, Context.WCharTy,
3367// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003368 Context.SignedCharTy, Context.ShortTy,
3369 Context.UnsignedCharTy, Context.UnsignedShortTy,
3370 Context.IntTy, Context.LongTy, Context.LongLongTy,
3371 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3372 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3373 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003374 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3375 "Invalid first promoted integral type");
3376 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3377 == Context.UnsignedLongLongTy &&
3378 "Invalid last promoted integral type");
3379 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3380 "Invalid first promoted arithmetic type");
3381 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3382 == Context.LongDoubleTy &&
3383 "Invalid last promoted arithmetic type");
3384
Douglas Gregora11693b2008-11-12 17:17:38 +00003385 // Find all of the types that the arguments can convert to, but only
3386 // if the operator we're looking at has built-in operator candidates
3387 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003388 Qualifiers VisibleTypeConversionsQuals;
3389 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003390 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3391 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3392
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003393 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003394 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3395 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003396 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003397 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003398 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003399 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003400 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003401 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003402 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003403 true,
3404 (Op == OO_Exclaim ||
3405 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003406 Op == OO_PipePipe),
3407 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003408 }
3409
3410 bool isComparison = false;
3411 switch (Op) {
3412 case OO_None:
3413 case NUM_OVERLOADED_OPERATORS:
3414 assert(false && "Expected an overloaded operator");
3415 break;
3416
Douglas Gregord08452f2008-11-19 15:42:04 +00003417 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003418 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003419 goto UnaryStar;
3420 else
3421 goto BinaryStar;
3422 break;
3423
3424 case OO_Plus: // '+' is either unary or binary
3425 if (NumArgs == 1)
3426 goto UnaryPlus;
3427 else
3428 goto BinaryPlus;
3429 break;
3430
3431 case OO_Minus: // '-' is either unary or binary
3432 if (NumArgs == 1)
3433 goto UnaryMinus;
3434 else
3435 goto BinaryMinus;
3436 break;
3437
3438 case OO_Amp: // '&' is either unary or binary
3439 if (NumArgs == 1)
3440 goto UnaryAmp;
3441 else
3442 goto BinaryAmp;
3443
3444 case OO_PlusPlus:
3445 case OO_MinusMinus:
3446 // C++ [over.built]p3:
3447 //
3448 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3449 // is either volatile or empty, there exist candidate operator
3450 // functions of the form
3451 //
3452 // VQ T& operator++(VQ T&);
3453 // T operator++(VQ T&, int);
3454 //
3455 // C++ [over.built]p4:
3456 //
3457 // For every pair (T, VQ), where T is an arithmetic type other
3458 // than bool, and VQ is either volatile or empty, there exist
3459 // candidate operator functions of the form
3460 //
3461 // VQ T& operator--(VQ T&);
3462 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003463 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003464 Arith < NumArithmeticTypes; ++Arith) {
3465 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003466 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003467 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003468
3469 // Non-volatile version.
3470 if (NumArgs == 1)
3471 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3472 else
3473 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003474 // heuristic to reduce number of builtin candidates in the set.
3475 // Add volatile version only if there are conversions to a volatile type.
3476 if (VisibleTypeConversionsQuals.hasVolatile()) {
3477 // Volatile version
3478 ParamTypes[0]
3479 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3480 if (NumArgs == 1)
3481 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3482 else
3483 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3484 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003485 }
3486
3487 // C++ [over.built]p5:
3488 //
3489 // For every pair (T, VQ), where T is a cv-qualified or
3490 // cv-unqualified object type, and VQ is either volatile or
3491 // empty, there exist candidate operator functions of the form
3492 //
3493 // T*VQ& operator++(T*VQ&);
3494 // T*VQ& operator--(T*VQ&);
3495 // T* operator++(T*VQ&, int);
3496 // T* operator--(T*VQ&, int);
3497 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3498 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3499 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003500 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003501 continue;
3502
Mike Stump11289f42009-09-09 15:08:12 +00003503 QualType ParamTypes[2] = {
3504 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003505 };
Mike Stump11289f42009-09-09 15:08:12 +00003506
Douglas Gregord08452f2008-11-19 15:42:04 +00003507 // Without volatile
3508 if (NumArgs == 1)
3509 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3510 else
3511 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3512
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003513 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3514 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003515 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003516 ParamTypes[0]
3517 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003518 if (NumArgs == 1)
3519 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3520 else
3521 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3522 }
3523 }
3524 break;
3525
3526 UnaryStar:
3527 // C++ [over.built]p6:
3528 // For every cv-qualified or cv-unqualified object type T, there
3529 // exist candidate operator functions of the form
3530 //
3531 // T& operator*(T*);
3532 //
3533 // C++ [over.built]p7:
3534 // For every function type T, there exist candidate operator
3535 // functions of the form
3536 // T& operator*(T*);
3537 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3538 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3539 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003540 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003541 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003542 &ParamTy, Args, 1, CandidateSet);
3543 }
3544 break;
3545
3546 UnaryPlus:
3547 // C++ [over.built]p8:
3548 // For every type T, there exist candidate operator functions of
3549 // the form
3550 //
3551 // T* operator+(T*);
3552 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3553 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3554 QualType ParamTy = *Ptr;
3555 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3556 }
Mike Stump11289f42009-09-09 15:08:12 +00003557
Douglas Gregord08452f2008-11-19 15:42:04 +00003558 // Fall through
3559
3560 UnaryMinus:
3561 // C++ [over.built]p9:
3562 // For every promoted arithmetic type T, there exist candidate
3563 // operator functions of the form
3564 //
3565 // T operator+(T);
3566 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003567 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003568 Arith < LastPromotedArithmeticType; ++Arith) {
3569 QualType ArithTy = ArithmeticTypes[Arith];
3570 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3571 }
3572 break;
3573
3574 case OO_Tilde:
3575 // C++ [over.built]p10:
3576 // For every promoted integral type T, there exist candidate
3577 // operator functions of the form
3578 //
3579 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003580 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003581 Int < LastPromotedIntegralType; ++Int) {
3582 QualType IntTy = ArithmeticTypes[Int];
3583 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3584 }
3585 break;
3586
Douglas Gregora11693b2008-11-12 17:17:38 +00003587 case OO_New:
3588 case OO_Delete:
3589 case OO_Array_New:
3590 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003591 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003592 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003593 break;
3594
3595 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003596 UnaryAmp:
3597 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003598 // C++ [over.match.oper]p3:
3599 // -- For the operator ',', the unary operator '&', or the
3600 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003601 break;
3602
Douglas Gregor84605ae2009-08-24 13:43:27 +00003603 case OO_EqualEqual:
3604 case OO_ExclaimEqual:
3605 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003606 // For every pointer to member type T, there exist candidate operator
3607 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003608 //
3609 // bool operator==(T,T);
3610 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003611 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003612 MemPtr = CandidateTypes.member_pointer_begin(),
3613 MemPtrEnd = CandidateTypes.member_pointer_end();
3614 MemPtr != MemPtrEnd;
3615 ++MemPtr) {
3616 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3617 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3618 }
Mike Stump11289f42009-09-09 15:08:12 +00003619
Douglas Gregor84605ae2009-08-24 13:43:27 +00003620 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003621
Douglas Gregora11693b2008-11-12 17:17:38 +00003622 case OO_Less:
3623 case OO_Greater:
3624 case OO_LessEqual:
3625 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003626 // C++ [over.built]p15:
3627 //
3628 // For every pointer or enumeration type T, there exist
3629 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003630 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003631 // bool operator<(T, T);
3632 // bool operator>(T, T);
3633 // bool operator<=(T, T);
3634 // bool operator>=(T, T);
3635 // bool operator==(T, T);
3636 // bool operator!=(T, T);
3637 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3638 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3639 QualType ParamTypes[2] = { *Ptr, *Ptr };
3640 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3641 }
Mike Stump11289f42009-09-09 15:08:12 +00003642 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003643 = CandidateTypes.enumeration_begin();
3644 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3645 QualType ParamTypes[2] = { *Enum, *Enum };
3646 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3647 }
3648
3649 // Fall through.
3650 isComparison = true;
3651
Douglas Gregord08452f2008-11-19 15:42:04 +00003652 BinaryPlus:
3653 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003654 if (!isComparison) {
3655 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3656
3657 // C++ [over.built]p13:
3658 //
3659 // For every cv-qualified or cv-unqualified object type T
3660 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003661 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003662 // T* operator+(T*, ptrdiff_t);
3663 // T& operator[](T*, ptrdiff_t); [BELOW]
3664 // T* operator-(T*, ptrdiff_t);
3665 // T* operator+(ptrdiff_t, T*);
3666 // T& operator[](ptrdiff_t, T*); [BELOW]
3667 //
3668 // C++ [over.built]p14:
3669 //
3670 // For every T, where T is a pointer to object type, there
3671 // exist candidate operator functions of the form
3672 //
3673 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003674 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003675 = CandidateTypes.pointer_begin();
3676 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3677 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3678
3679 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3680 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3681
3682 if (Op == OO_Plus) {
3683 // T* operator+(ptrdiff_t, T*);
3684 ParamTypes[0] = ParamTypes[1];
3685 ParamTypes[1] = *Ptr;
3686 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3687 } else {
3688 // ptrdiff_t operator-(T, T);
3689 ParamTypes[1] = *Ptr;
3690 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3691 Args, 2, CandidateSet);
3692 }
3693 }
3694 }
3695 // Fall through
3696
Douglas Gregora11693b2008-11-12 17:17:38 +00003697 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003698 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003699 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003700 // C++ [over.built]p12:
3701 //
3702 // For every pair of promoted arithmetic types L and R, there
3703 // exist candidate operator functions of the form
3704 //
3705 // LR operator*(L, R);
3706 // LR operator/(L, R);
3707 // LR operator+(L, R);
3708 // LR operator-(L, R);
3709 // bool operator<(L, R);
3710 // bool operator>(L, R);
3711 // bool operator<=(L, R);
3712 // bool operator>=(L, R);
3713 // bool operator==(L, R);
3714 // bool operator!=(L, R);
3715 //
3716 // where LR is the result of the usual arithmetic conversions
3717 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003718 //
3719 // C++ [over.built]p24:
3720 //
3721 // For every pair of promoted arithmetic types L and R, there exist
3722 // candidate operator functions of the form
3723 //
3724 // LR operator?(bool, L, R);
3725 //
3726 // where LR is the result of the usual arithmetic conversions
3727 // between types L and R.
3728 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003729 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003730 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003731 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003732 Right < LastPromotedArithmeticType; ++Right) {
3733 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003734 QualType Result
3735 = isComparison
3736 ? Context.BoolTy
3737 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003738 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3739 }
3740 }
3741 break;
3742
3743 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003744 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003745 case OO_Caret:
3746 case OO_Pipe:
3747 case OO_LessLess:
3748 case OO_GreaterGreater:
3749 // C++ [over.built]p17:
3750 //
3751 // For every pair of promoted integral types L and R, there
3752 // exist candidate operator functions of the form
3753 //
3754 // LR operator%(L, R);
3755 // LR operator&(L, R);
3756 // LR operator^(L, R);
3757 // LR operator|(L, R);
3758 // L operator<<(L, R);
3759 // L operator>>(L, R);
3760 //
3761 // where LR is the result of the usual arithmetic conversions
3762 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003763 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003764 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003765 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003766 Right < LastPromotedIntegralType; ++Right) {
3767 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3768 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3769 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003770 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003771 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3772 }
3773 }
3774 break;
3775
3776 case OO_Equal:
3777 // C++ [over.built]p20:
3778 //
3779 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003780 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003781 // empty, there exist candidate operator functions of the form
3782 //
3783 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003784 for (BuiltinCandidateTypeSet::iterator
3785 Enum = CandidateTypes.enumeration_begin(),
3786 EnumEnd = CandidateTypes.enumeration_end();
3787 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003788 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003789 CandidateSet);
3790 for (BuiltinCandidateTypeSet::iterator
3791 MemPtr = CandidateTypes.member_pointer_begin(),
3792 MemPtrEnd = CandidateTypes.member_pointer_end();
3793 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003794 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003795 CandidateSet);
3796 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003797
3798 case OO_PlusEqual:
3799 case OO_MinusEqual:
3800 // C++ [over.built]p19:
3801 //
3802 // For every pair (T, VQ), where T is any type and VQ is either
3803 // volatile or empty, there exist candidate operator functions
3804 // of the form
3805 //
3806 // T*VQ& operator=(T*VQ&, T*);
3807 //
3808 // C++ [over.built]p21:
3809 //
3810 // For every pair (T, VQ), where T is a cv-qualified or
3811 // cv-unqualified object type and VQ is either volatile or
3812 // empty, there exist candidate operator functions of the form
3813 //
3814 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3815 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3816 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3817 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3818 QualType ParamTypes[2];
3819 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3820
3821 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003822 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003823 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3824 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003825
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003826 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3827 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003828 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003829 ParamTypes[0]
3830 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003831 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3832 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003833 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003834 }
3835 // Fall through.
3836
3837 case OO_StarEqual:
3838 case OO_SlashEqual:
3839 // C++ [over.built]p18:
3840 //
3841 // For every triple (L, VQ, R), where L is an arithmetic type,
3842 // VQ is either volatile or empty, and R is a promoted
3843 // arithmetic type, there exist candidate operator functions of
3844 // the form
3845 //
3846 // VQ L& operator=(VQ L&, R);
3847 // VQ L& operator*=(VQ L&, R);
3848 // VQ L& operator/=(VQ L&, R);
3849 // VQ L& operator+=(VQ L&, R);
3850 // VQ L& operator-=(VQ L&, R);
3851 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003852 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003853 Right < LastPromotedArithmeticType; ++Right) {
3854 QualType ParamTypes[2];
3855 ParamTypes[1] = ArithmeticTypes[Right];
3856
3857 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003858 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003859 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3860 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003861
3862 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003863 if (VisibleTypeConversionsQuals.hasVolatile()) {
3864 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3865 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3866 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3867 /*IsAssigmentOperator=*/Op == OO_Equal);
3868 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003869 }
3870 }
3871 break;
3872
3873 case OO_PercentEqual:
3874 case OO_LessLessEqual:
3875 case OO_GreaterGreaterEqual:
3876 case OO_AmpEqual:
3877 case OO_CaretEqual:
3878 case OO_PipeEqual:
3879 // C++ [over.built]p22:
3880 //
3881 // For every triple (L, VQ, R), where L is an integral type, VQ
3882 // is either volatile or empty, and R is a promoted integral
3883 // type, there exist candidate operator functions of the form
3884 //
3885 // VQ L& operator%=(VQ L&, R);
3886 // VQ L& operator<<=(VQ L&, R);
3887 // VQ L& operator>>=(VQ L&, R);
3888 // VQ L& operator&=(VQ L&, R);
3889 // VQ L& operator^=(VQ L&, R);
3890 // VQ L& operator|=(VQ L&, R);
3891 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003892 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003893 Right < LastPromotedIntegralType; ++Right) {
3894 QualType ParamTypes[2];
3895 ParamTypes[1] = ArithmeticTypes[Right];
3896
3897 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003898 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003899 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00003900 if (VisibleTypeConversionsQuals.hasVolatile()) {
3901 // Add this built-in operator as a candidate (VQ is 'volatile').
3902 ParamTypes[0] = ArithmeticTypes[Left];
3903 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3904 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3905 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3906 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003907 }
3908 }
3909 break;
3910
Douglas Gregord08452f2008-11-19 15:42:04 +00003911 case OO_Exclaim: {
3912 // C++ [over.operator]p23:
3913 //
3914 // There also exist candidate operator functions of the form
3915 //
Mike Stump11289f42009-09-09 15:08:12 +00003916 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003917 // bool operator&&(bool, bool); [BELOW]
3918 // bool operator||(bool, bool); [BELOW]
3919 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003920 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3921 /*IsAssignmentOperator=*/false,
3922 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003923 break;
3924 }
3925
Douglas Gregora11693b2008-11-12 17:17:38 +00003926 case OO_AmpAmp:
3927 case OO_PipePipe: {
3928 // C++ [over.operator]p23:
3929 //
3930 // There also exist candidate operator functions of the form
3931 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003932 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003933 // bool operator&&(bool, bool);
3934 // bool operator||(bool, bool);
3935 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003936 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3937 /*IsAssignmentOperator=*/false,
3938 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003939 break;
3940 }
3941
3942 case OO_Subscript:
3943 // C++ [over.built]p13:
3944 //
3945 // For every cv-qualified or cv-unqualified object type T there
3946 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003947 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003948 // T* operator+(T*, ptrdiff_t); [ABOVE]
3949 // T& operator[](T*, ptrdiff_t);
3950 // T* operator-(T*, ptrdiff_t); [ABOVE]
3951 // T* operator+(ptrdiff_t, T*); [ABOVE]
3952 // T& operator[](ptrdiff_t, T*);
3953 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3954 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3955 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003956 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003957 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003958
3959 // T& operator[](T*, ptrdiff_t)
3960 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3961
3962 // T& operator[](ptrdiff_t, T*);
3963 ParamTypes[0] = ParamTypes[1];
3964 ParamTypes[1] = *Ptr;
3965 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3966 }
3967 break;
3968
3969 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003970 // C++ [over.built]p11:
3971 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3972 // C1 is the same type as C2 or is a derived class of C2, T is an object
3973 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3974 // there exist candidate operator functions of the form
3975 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3976 // where CV12 is the union of CV1 and CV2.
3977 {
3978 for (BuiltinCandidateTypeSet::iterator Ptr =
3979 CandidateTypes.pointer_begin();
3980 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3981 QualType C1Ty = (*Ptr);
3982 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003983 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003984 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003985 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003986 if (!isa<RecordType>(C1))
3987 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003988 // heuristic to reduce number of builtin candidates in the set.
3989 // Add volatile/restrict version only if there are conversions to a
3990 // volatile/restrict type.
3991 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3992 continue;
3993 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3994 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003995 }
3996 for (BuiltinCandidateTypeSet::iterator
3997 MemPtr = CandidateTypes.member_pointer_begin(),
3998 MemPtrEnd = CandidateTypes.member_pointer_end();
3999 MemPtr != MemPtrEnd; ++MemPtr) {
4000 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4001 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004002 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004003 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4004 break;
4005 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4006 // build CV12 T&
4007 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004008 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4009 T.isVolatileQualified())
4010 continue;
4011 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4012 T.isRestrictQualified())
4013 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004014 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004015 QualType ResultTy = Context.getLValueReferenceType(T);
4016 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4017 }
4018 }
4019 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004020 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004021
4022 case OO_Conditional:
4023 // Note that we don't consider the first argument, since it has been
4024 // contextually converted to bool long ago. The candidates below are
4025 // therefore added as binary.
4026 //
4027 // C++ [over.built]p24:
4028 // For every type T, where T is a pointer or pointer-to-member type,
4029 // there exist candidate operator functions of the form
4030 //
4031 // T operator?(bool, T, T);
4032 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004033 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4034 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4035 QualType ParamTypes[2] = { *Ptr, *Ptr };
4036 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4037 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004038 for (BuiltinCandidateTypeSet::iterator Ptr =
4039 CandidateTypes.member_pointer_begin(),
4040 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4041 QualType ParamTypes[2] = { *Ptr, *Ptr };
4042 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4043 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004044 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004045 }
4046}
4047
Douglas Gregore254f902009-02-04 00:32:51 +00004048/// \brief Add function candidates found via argument-dependent lookup
4049/// to the set of overloading candidates.
4050///
4051/// This routine performs argument-dependent name lookup based on the
4052/// given function name (which may also be an operator name) and adds
4053/// all of the overload candidates found by ADL to the overload
4054/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004055void
Douglas Gregore254f902009-02-04 00:32:51 +00004056Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
4057 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004058 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004059 OverloadCandidateSet& CandidateSet,
4060 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004061 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00004062
Douglas Gregorcabea402009-09-22 15:41:20 +00004063 // FIXME: Should we be trafficking in canonical function decls throughout?
4064
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004065 // Record all of the function candidates that we've already
4066 // added to the overload set, so that we don't add those same
4067 // candidates a second time.
4068 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4069 CandEnd = CandidateSet.end();
4070 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004071 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004072 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004073 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4074 Functions.insert(FunTmpl);
4075 }
Douglas Gregore254f902009-02-04 00:32:51 +00004076
Douglas Gregorcabea402009-09-22 15:41:20 +00004077 // FIXME: Pass in the explicit template arguments?
Sebastian Redlc057f422009-10-23 19:23:15 +00004078 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00004079
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004080 // Erase all of the candidates we already knew about.
4081 // FIXME: This is suboptimal. Is there a better way?
4082 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4083 CandEnd = CandidateSet.end();
4084 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004085 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004086 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004087 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4088 Functions.erase(FunTmpl);
4089 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004090
4091 // For each of the ADL candidates we found, add it to the overload
4092 // set.
4093 for (FunctionSet::iterator Func = Functions.begin(),
4094 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00004095 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00004096 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
John McCall6b51f282009-11-23 01:53:49 +00004097 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004098 continue;
4099
4100 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
4101 false, false, PartialOverloading);
4102 } else
Mike Stump11289f42009-09-09 15:08:12 +00004103 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00004104 ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004105 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004106 }
Douglas Gregore254f902009-02-04 00:32:51 +00004107}
4108
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004109/// isBetterOverloadCandidate - Determines whether the first overload
4110/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004111bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004112Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00004113 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004114 // Define viable functions to be better candidates than non-viable
4115 // functions.
4116 if (!Cand2.Viable)
4117 return Cand1.Viable;
4118 else if (!Cand1.Viable)
4119 return false;
4120
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004121 // C++ [over.match.best]p1:
4122 //
4123 // -- if F is a static member function, ICS1(F) is defined such
4124 // that ICS1(F) is neither better nor worse than ICS1(G) for
4125 // any function G, and, symmetrically, ICS1(G) is neither
4126 // better nor worse than ICS1(F).
4127 unsigned StartArg = 0;
4128 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4129 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004130
Douglas Gregord3cb3562009-07-07 23:38:56 +00004131 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004132 // A viable function F1 is defined to be a better function than another
4133 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004134 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004135 unsigned NumArgs = Cand1.Conversions.size();
4136 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4137 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004138 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004139 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4140 Cand2.Conversions[ArgIdx])) {
4141 case ImplicitConversionSequence::Better:
4142 // Cand1 has a better conversion sequence.
4143 HasBetterConversion = true;
4144 break;
4145
4146 case ImplicitConversionSequence::Worse:
4147 // Cand1 can't be better than Cand2.
4148 return false;
4149
4150 case ImplicitConversionSequence::Indistinguishable:
4151 // Do nothing.
4152 break;
4153 }
4154 }
4155
Mike Stump11289f42009-09-09 15:08:12 +00004156 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004157 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004158 if (HasBetterConversion)
4159 return true;
4160
Mike Stump11289f42009-09-09 15:08:12 +00004161 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004162 // specialization, or, if not that,
4163 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4164 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4165 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004166
4167 // -- F1 and F2 are function template specializations, and the function
4168 // template for F1 is more specialized than the template for F2
4169 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004170 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004171 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4172 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004173 if (FunctionTemplateDecl *BetterTemplate
4174 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4175 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00004176 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4177 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004178 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004179
Douglas Gregora1f013e2008-11-07 22:36:19 +00004180 // -- the context is an initialization by user-defined conversion
4181 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4182 // from the return type of F1 to the destination type (i.e.,
4183 // the type of the entity being initialized) is a better
4184 // conversion sequence than the standard conversion sequence
4185 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004186 if (Cand1.Function && Cand2.Function &&
4187 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004188 isa<CXXConversionDecl>(Cand2.Function)) {
4189 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4190 Cand2.FinalConversion)) {
4191 case ImplicitConversionSequence::Better:
4192 // Cand1 has a better conversion sequence.
4193 return true;
4194
4195 case ImplicitConversionSequence::Worse:
4196 // Cand1 can't be better than Cand2.
4197 return false;
4198
4199 case ImplicitConversionSequence::Indistinguishable:
4200 // Do nothing
4201 break;
4202 }
4203 }
4204
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004205 return false;
4206}
4207
Mike Stump11289f42009-09-09 15:08:12 +00004208/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004209/// within an overload candidate set.
4210///
4211/// \param CandidateSet the set of candidate functions.
4212///
4213/// \param Loc the location of the function name (or operator symbol) for
4214/// which overload resolution occurs.
4215///
Mike Stump11289f42009-09-09 15:08:12 +00004216/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004217/// function, Best points to the candidate function found.
4218///
4219/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004220OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4221 SourceLocation Loc,
4222 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004223 // Find the best viable function.
4224 Best = CandidateSet.end();
4225 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4226 Cand != CandidateSet.end(); ++Cand) {
4227 if (Cand->Viable) {
4228 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4229 Best = Cand;
4230 }
4231 }
4232
4233 // If we didn't find any viable functions, abort.
4234 if (Best == CandidateSet.end())
4235 return OR_No_Viable_Function;
4236
4237 // Make sure that this function is better than every other viable
4238 // function. If not, we have an ambiguity.
4239 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4240 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004241 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004242 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00004243 !isBetterOverloadCandidate(*Best, *Cand)) {
4244 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004245 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004246 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004247 }
Mike Stump11289f42009-09-09 15:08:12 +00004248
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004249 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004250 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004251 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004252 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004253 return OR_Deleted;
4254
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004255 // C++ [basic.def.odr]p2:
4256 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004257 // when referred to from a potentially-evaluated expression. [Note: this
4258 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004259 // (clause 13), user-defined conversions (12.3.2), allocation function for
4260 // placement new (5.3.4), as well as non-default initialization (8.5).
4261 if (Best->Function)
4262 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004263 return OR_Success;
4264}
4265
John McCall53262c92010-01-12 02:15:36 +00004266namespace {
4267
4268enum OverloadCandidateKind {
4269 oc_function,
4270 oc_method,
4271 oc_constructor,
4272 oc_implicit_default_constructor,
4273 oc_implicit_copy_constructor,
4274 oc_implicit_copy_assignment,
4275 oc_template_specialization // function, constructor, or conversion template
4276};
4277
4278OverloadCandidateKind ClassifyOverloadCandidate(FunctionDecl *Fn) {
4279 if (Fn->getPrimaryTemplate())
4280 return oc_template_specialization;
John McCallfd0b2f82010-01-06 09:43:14 +00004281
4282 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004283 if (!Ctor->isImplicit())
4284 return oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004285
John McCall53262c92010-01-12 02:15:36 +00004286 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4287 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004288 }
4289
4290 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4291 // This actually gets spelled 'candidate function' for now, but
4292 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004293 if (!Meth->isImplicit())
4294 return oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004295
4296 assert(Meth->isCopyAssignment()
4297 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004298 return oc_implicit_copy_assignment;
4299 }
4300
4301 return oc_function;
4302}
4303
4304std::string DescribeFunctionTemplate(Sema &S, FunctionDecl *Fn) {
4305 FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate();
4306 return S.getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4307 *Fn->getTemplateSpecializationArgs());
4308}
4309
4310} // end anonymous namespace
4311
4312// Notes the location of an overload candidate.
4313void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
4314 OverloadCandidateKind K = ClassifyOverloadCandidate(Fn);
4315 if (K == oc_template_specialization) {
4316 Diag(Fn->getLocation(), diag::note_ovl_template_candidate)
4317 << DescribeFunctionTemplate(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00004318 return;
4319 }
4320
John McCall53262c92010-01-12 02:15:36 +00004321 Diag(Fn->getLocation(), diag::note_ovl_candidate) << (unsigned) K;
John McCallfd0b2f82010-01-06 09:43:14 +00004322}
4323
John McCall0d1da222010-01-12 00:44:57 +00004324/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4325/// "lead" diagnostic; it will be given two arguments, the source and
4326/// target types of the conversion.
4327void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4328 SourceLocation CaretLoc,
4329 const PartialDiagnostic &PDiag) {
4330 Diag(CaretLoc, PDiag)
4331 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4332 for (AmbiguousConversionSequence::const_iterator
4333 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4334 NoteOverloadCandidate(*I);
4335 }
John McCall12f97bc2010-01-08 04:41:39 +00004336}
4337
John McCall0d1da222010-01-12 00:44:57 +00004338namespace {
4339
John McCalld3224162010-01-08 00:58:21 +00004340void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand) {
John McCall53262c92010-01-12 02:15:36 +00004341 FunctionDecl *Fn = Cand->Function;
4342
John McCall12f97bc2010-01-08 04:41:39 +00004343 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00004344 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
4345 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(Fn);
4346
4347 if (FnKind == oc_template_specialization) {
4348 S.Diag(Fn->getLocation(), diag::note_ovl_template_candidate_deleted)
4349 << DescribeFunctionTemplate(S, Fn) << Fn->isDeleted();
4350 return;
4351 }
4352
4353 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
4354 << FnKind << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00004355 return;
John McCall12f97bc2010-01-08 04:41:39 +00004356 }
4357
John McCalld3224162010-01-08 00:58:21 +00004358 bool errReported = false;
4359 if (!Cand->Viable && Cand->Conversions.size() > 0) {
4360 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4361 const ImplicitConversionSequence &Conversion =
4362 Cand->Conversions[i];
John McCall0d1da222010-01-12 00:44:57 +00004363
4364 if (!Conversion.isAmbiguous())
John McCalld3224162010-01-08 00:58:21 +00004365 continue;
John McCall0d1da222010-01-12 00:44:57 +00004366
John McCall53262c92010-01-12 02:15:36 +00004367 S.DiagnoseAmbiguousConversion(Conversion, Fn->getLocation(),
John McCall0d1da222010-01-12 00:44:57 +00004368 PDiag(diag::note_ovl_candidate_not_viable) << (i+1));
John McCalld3224162010-01-08 00:58:21 +00004369 errReported = true;
John McCalld3224162010-01-08 00:58:21 +00004370 }
4371 }
4372
4373 if (!errReported)
John McCall53262c92010-01-12 02:15:36 +00004374 S.NoteOverloadCandidate(Fn);
John McCalld3224162010-01-08 00:58:21 +00004375}
4376
4377void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4378 // Desugar the type of the surrogate down to a function type,
4379 // retaining as many typedefs as possible while still showing
4380 // the function type (and, therefore, its parameter types).
4381 QualType FnType = Cand->Surrogate->getConversionType();
4382 bool isLValueReference = false;
4383 bool isRValueReference = false;
4384 bool isPointer = false;
4385 if (const LValueReferenceType *FnTypeRef =
4386 FnType->getAs<LValueReferenceType>()) {
4387 FnType = FnTypeRef->getPointeeType();
4388 isLValueReference = true;
4389 } else if (const RValueReferenceType *FnTypeRef =
4390 FnType->getAs<RValueReferenceType>()) {
4391 FnType = FnTypeRef->getPointeeType();
4392 isRValueReference = true;
4393 }
4394 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4395 FnType = FnTypePtr->getPointeeType();
4396 isPointer = true;
4397 }
4398 // Desugar down to a function type.
4399 FnType = QualType(FnType->getAs<FunctionType>(), 0);
4400 // Reconstruct the pointer/reference as appropriate.
4401 if (isPointer) FnType = S.Context.getPointerType(FnType);
4402 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
4403 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
4404
4405 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
4406 << FnType;
4407}
4408
4409void NoteBuiltinOperatorCandidate(Sema &S,
4410 const char *Opc,
4411 SourceLocation OpLoc,
4412 OverloadCandidate *Cand) {
4413 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
4414 std::string TypeStr("operator");
4415 TypeStr += Opc;
4416 TypeStr += "(";
4417 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4418 if (Cand->Conversions.size() == 1) {
4419 TypeStr += ")";
4420 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
4421 } else {
4422 TypeStr += ", ";
4423 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4424 TypeStr += ")";
4425 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
4426 }
4427}
4428
4429void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
4430 OverloadCandidate *Cand) {
4431 unsigned NoOperands = Cand->Conversions.size();
4432 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4433 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00004434 if (ICS.isBad()) break; // all meaningless after first invalid
4435 if (!ICS.isAmbiguous()) continue;
4436
4437 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
4438 PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00004439 }
4440}
4441
John McCallad2587a2010-01-12 00:48:53 +00004442struct CompareOverloadCandidatesForDisplay {
4443 Sema &S;
4444 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00004445
4446 bool operator()(const OverloadCandidate *L,
4447 const OverloadCandidate *R) {
4448 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00004449 if (L->Viable) {
4450 if (!R->Viable) return true;
4451
4452 // TODO: introduce a tri-valued comparison for overload
4453 // candidates. Would be more worthwhile if we had a sort
4454 // that could exploit it.
4455 if (S.isBetterOverloadCandidate(*L, *R)) return true;
4456 if (S.isBetterOverloadCandidate(*R, *L)) return false;
4457 } else if (R->Viable)
4458 return false;
John McCall12f97bc2010-01-08 04:41:39 +00004459
4460 // Put declared functions first.
4461 if (L->Function) {
4462 if (!R->Function) return true;
John McCallad2587a2010-01-12 00:48:53 +00004463 return S.SourceMgr.isBeforeInTranslationUnit(L->Function->getLocation(),
4464 R->Function->getLocation());
John McCall12f97bc2010-01-08 04:41:39 +00004465 } else if (R->Function) return false;
4466
4467 // Then surrogates.
4468 if (L->IsSurrogate) {
4469 if (!R->IsSurrogate) return true;
John McCallad2587a2010-01-12 00:48:53 +00004470 return S.SourceMgr.isBeforeInTranslationUnit(L->Surrogate->getLocation(),
4471 R->Surrogate->getLocation());
John McCall12f97bc2010-01-08 04:41:39 +00004472 } else if (R->IsSurrogate) return false;
4473
4474 // And builtins just come in a jumble.
4475 return false;
4476 }
4477};
4478
John McCalld3224162010-01-08 00:58:21 +00004479} // end anonymous namespace
4480
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004481/// PrintOverloadCandidates - When overload resolution fails, prints
4482/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00004483/// set.
Mike Stump11289f42009-09-09 15:08:12 +00004484void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004485Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00004486 OverloadCandidateDisplayKind OCD,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004487 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004488 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00004489 // Sort the candidates by viability and position. Sorting directly would
4490 // be prohibitive, so we make a set of pointers and sort those.
4491 llvm::SmallVector<OverloadCandidate*, 32> Cands;
4492 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
4493 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4494 LastCand = CandidateSet.end();
4495 Cand != LastCand; ++Cand)
4496 if (Cand->Viable || OCD == OCD_AllCandidates)
4497 Cands.push_back(Cand);
John McCallad2587a2010-01-12 00:48:53 +00004498 std::sort(Cands.begin(), Cands.end(),
4499 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00004500
John McCall0d1da222010-01-12 00:44:57 +00004501 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00004502
John McCall12f97bc2010-01-08 04:41:39 +00004503 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
4504 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
4505 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004506
John McCalld3224162010-01-08 00:58:21 +00004507 if (Cand->Function)
4508 NoteFunctionCandidate(*this, Cand);
4509 else if (Cand->IsSurrogate)
4510 NoteSurrogateCandidate(*this, Cand);
4511
4512 // This a builtin candidate. We do not, in general, want to list
4513 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00004514 else if (Cand->Viable) {
4515 // Generally we only see ambiguities including viable builtin
4516 // operators if overload resolution got screwed up by an
4517 // ambiguous user-defined conversion.
4518 //
4519 // FIXME: It's quite possible for different conversions to see
4520 // different ambiguities, though.
4521 if (!ReportedAmbiguousConversions) {
4522 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
4523 ReportedAmbiguousConversions = true;
4524 }
John McCalld3224162010-01-08 00:58:21 +00004525
John McCall0d1da222010-01-12 00:44:57 +00004526 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00004527 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00004528 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004529 }
4530}
4531
Douglas Gregorcd695e52008-11-10 20:40:00 +00004532/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4533/// an overloaded function (C++ [over.over]), where @p From is an
4534/// expression with overloaded function type and @p ToType is the type
4535/// we're trying to resolve to. For example:
4536///
4537/// @code
4538/// int f(double);
4539/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004540///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004541/// int (*pfd)(double) = f; // selects f(double)
4542/// @endcode
4543///
4544/// This routine returns the resulting FunctionDecl if it could be
4545/// resolved, and NULL otherwise. When @p Complain is true, this
4546/// routine will emit diagnostics if there is an error.
4547FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004548Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004549 bool Complain) {
4550 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004551 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004552 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004553 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004554 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004555 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004556 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004557 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004558 FunctionType = MemTypePtr->getPointeeType();
4559 IsMember = true;
4560 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004561
4562 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00004563 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00004564 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004565 return 0;
4566
4567 // Find the actual overloaded function declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004568
Douglas Gregorcd695e52008-11-10 20:40:00 +00004569 // C++ [over.over]p1:
4570 // [...] [Note: any redundant set of parentheses surrounding the
4571 // overloaded function name is ignored (5.1). ]
4572 Expr *OvlExpr = From->IgnoreParens();
4573
4574 // C++ [over.over]p1:
4575 // [...] The overloaded function name can be preceded by the &
4576 // operator.
4577 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4578 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4579 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4580 }
4581
Anders Carlssonb68b0282009-10-20 22:53:47 +00004582 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004583 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCalld14a8642009-11-21 08:51:07 +00004584
4585 llvm::SmallVector<NamedDecl*,8> Fns;
Anders Carlssonb68b0282009-10-20 22:53:47 +00004586
John McCall10eae182009-11-30 22:42:35 +00004587 // Look into the overloaded expression.
John McCalle66edc12009-11-24 19:00:30 +00004588 if (UnresolvedLookupExpr *UL
John McCalld14a8642009-11-21 08:51:07 +00004589 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4590 Fns.append(UL->decls_begin(), UL->decls_end());
John McCalle66edc12009-11-24 19:00:30 +00004591 if (UL->hasExplicitTemplateArgs()) {
4592 HasExplicitTemplateArgs = true;
4593 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4594 }
John McCall10eae182009-11-30 22:42:35 +00004595 } else if (UnresolvedMemberExpr *ME
4596 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4597 Fns.append(ME->decls_begin(), ME->decls_end());
4598 if (ME->hasExplicitTemplateArgs()) {
4599 HasExplicitTemplateArgs = true;
John McCall6b51f282009-11-23 01:53:49 +00004600 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004601 }
Douglas Gregor9b146582009-07-08 20:55:45 +00004602 }
Mike Stump11289f42009-09-09 15:08:12 +00004603
John McCalld14a8642009-11-21 08:51:07 +00004604 // If we didn't actually find anything, we're done.
4605 if (Fns.empty())
4606 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004607
Douglas Gregorcd695e52008-11-10 20:40:00 +00004608 // Look through all of the overloaded functions, searching for one
4609 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004610 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004611 bool FoundNonTemplateFunction = false;
John McCalld14a8642009-11-21 08:51:07 +00004612 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4613 E = Fns.end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004614 // Look through any using declarations to find the underlying function.
4615 NamedDecl *Fn = (*I)->getUnderlyingDecl();
4616
Douglas Gregorcd695e52008-11-10 20:40:00 +00004617 // C++ [over.over]p3:
4618 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00004619 // targets of type "pointer-to-function" or "reference-to-function."
4620 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004621 // type "pointer-to-member-function."
4622 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004623
Mike Stump11289f42009-09-09 15:08:12 +00004624 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004625 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00004626 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004627 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004628 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004629 // static when converting to member pointer.
4630 if (Method->isStatic() == IsMember)
4631 continue;
4632 } else if (IsMember)
4633 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004634
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004635 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004636 // If the name is a function template, template argument deduction is
4637 // done (14.8.2.2), and if the argument deduction succeeds, the
4638 // resulting template argument list is used to generate a single
4639 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004640 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004641 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00004642 FunctionDecl *Specialization = 0;
4643 TemplateDeductionInfo Info(Context);
4644 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004645 = DeduceTemplateArguments(FunctionTemplate,
4646 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
Douglas Gregor9b146582009-07-08 20:55:45 +00004647 FunctionType, Specialization, Info)) {
4648 // FIXME: make a note of the failed deduction for diagnostics.
4649 (void)Result;
4650 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004651 // FIXME: If the match isn't exact, shouldn't we just drop this as
4652 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00004653 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004654 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004655 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004656 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004657 }
John McCalld14a8642009-11-21 08:51:07 +00004658
4659 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00004660 }
Mike Stump11289f42009-09-09 15:08:12 +00004661
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004662 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004663 // Skip non-static functions when converting to pointer, and static
4664 // when converting to member pointer.
4665 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004666 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00004667
4668 // If we have explicit template arguments, skip non-templates.
4669 if (HasExplicitTemplateArgs)
4670 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004671 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004672 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004673
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004674 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00004675 QualType ResultTy;
4676 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
4677 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
4678 ResultTy)) {
John McCalld14a8642009-11-21 08:51:07 +00004679 Matches.insert(cast<FunctionDecl>(FunDecl->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004680 FoundNonTemplateFunction = true;
4681 }
Mike Stump11289f42009-09-09 15:08:12 +00004682 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004683 }
4684
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004685 // If there were 0 or 1 matches, we're done.
4686 if (Matches.empty())
4687 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004688 else if (Matches.size() == 1) {
4689 FunctionDecl *Result = *Matches.begin();
4690 MarkDeclarationReferenced(From->getLocStart(), Result);
4691 return Result;
4692 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004693
4694 // C++ [over.over]p4:
4695 // If more than one function is selected, [...]
Douglas Gregor05155d82009-08-21 23:19:43 +00004696 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorfae1d712009-09-26 03:56:17 +00004697 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004698 // [...] and any given function template specialization F1 is
4699 // eliminated if the set contains a second function template
4700 // specialization whose function template is more specialized
4701 // than the function template of F1 according to the partial
4702 // ordering rules of 14.5.5.2.
4703
4704 // The algorithm specified above is quadratic. We instead use a
4705 // two-pass algorithm (similar to the one used to identify the
4706 // best viable function in an overload set) that identifies the
4707 // best function template (if it exists).
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004708 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregorfae1d712009-09-26 03:56:17 +00004709 Matches.end());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004710 FunctionDecl *Result =
4711 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4712 TPOC_Other, From->getLocStart(),
4713 PDiag(),
4714 PDiag(diag::err_addr_ovl_ambiguous)
4715 << TemplateMatches[0]->getDeclName(),
John McCallfd0b2f82010-01-06 09:43:14 +00004716 PDiag(diag::note_ovl_template_candidate));
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004717 MarkDeclarationReferenced(From->getLocStart(), Result);
4718 return Result;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004719 }
Mike Stump11289f42009-09-09 15:08:12 +00004720
Douglas Gregorfae1d712009-09-26 03:56:17 +00004721 // [...] any function template specializations in the set are
4722 // eliminated if the set also contains a non-template function, [...]
4723 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4724 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4725 if ((*M)->getPrimaryTemplate() == 0)
4726 RemainingMatches.push_back(*M);
4727
Mike Stump11289f42009-09-09 15:08:12 +00004728 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004729 // selected function.
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004730 if (RemainingMatches.size() == 1) {
4731 FunctionDecl *Result = RemainingMatches.front();
4732 MarkDeclarationReferenced(From->getLocStart(), Result);
4733 return Result;
4734 }
Mike Stump11289f42009-09-09 15:08:12 +00004735
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004736 // FIXME: We should probably return the same thing that BestViableFunction
4737 // returns (even if we issue the diagnostics here).
4738 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4739 << RemainingMatches[0]->getDeclName();
4740 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
John McCallfd0b2f82010-01-06 09:43:14 +00004741 NoteOverloadCandidate(RemainingMatches[I]);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004742 return 0;
4743}
4744
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004745/// \brief Given an expression that refers to an overloaded function, try to
4746/// resolve that overloaded function expression down to a single function.
4747///
4748/// This routine can only resolve template-ids that refer to a single function
4749/// template, where that template-id refers to a single template whose template
4750/// arguments are either provided by the template-id or have defaults,
4751/// as described in C++0x [temp.arg.explicit]p3.
4752FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
4753 // C++ [over.over]p1:
4754 // [...] [Note: any redundant set of parentheses surrounding the
4755 // overloaded function name is ignored (5.1). ]
4756 Expr *OvlExpr = From->IgnoreParens();
4757
4758 // C++ [over.over]p1:
4759 // [...] The overloaded function name can be preceded by the &
4760 // operator.
4761 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4762 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4763 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4764 }
4765
4766 bool HasExplicitTemplateArgs = false;
4767 TemplateArgumentListInfo ExplicitTemplateArgs;
4768
4769 llvm::SmallVector<NamedDecl*,8> Fns;
4770
4771 // Look into the overloaded expression.
4772 if (UnresolvedLookupExpr *UL
4773 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4774 Fns.append(UL->decls_begin(), UL->decls_end());
4775 if (UL->hasExplicitTemplateArgs()) {
4776 HasExplicitTemplateArgs = true;
4777 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4778 }
4779 } else if (UnresolvedMemberExpr *ME
4780 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4781 Fns.append(ME->decls_begin(), ME->decls_end());
4782 if (ME->hasExplicitTemplateArgs()) {
4783 HasExplicitTemplateArgs = true;
4784 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4785 }
4786 }
4787
4788 // If we didn't actually find any template-ids, we're done.
4789 if (Fns.empty() || !HasExplicitTemplateArgs)
4790 return 0;
4791
4792 // Look through all of the overloaded functions, searching for one
4793 // whose type matches exactly.
4794 FunctionDecl *Matched = 0;
4795 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4796 E = Fns.end(); I != E; ++I) {
4797 // C++0x [temp.arg.explicit]p3:
4798 // [...] In contexts where deduction is done and fails, or in contexts
4799 // where deduction is not done, if a template argument list is
4800 // specified and it, along with any default template arguments,
4801 // identifies a single function template specialization, then the
4802 // template-id is an lvalue for the function template specialization.
4803 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
4804
4805 // C++ [over.over]p2:
4806 // If the name is a function template, template argument deduction is
4807 // done (14.8.2.2), and if the argument deduction succeeds, the
4808 // resulting template argument list is used to generate a single
4809 // function template specialization, which is added to the set of
4810 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004811 FunctionDecl *Specialization = 0;
4812 TemplateDeductionInfo Info(Context);
4813 if (TemplateDeductionResult Result
4814 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
4815 Specialization, Info)) {
4816 // FIXME: make a note of the failed deduction for diagnostics.
4817 (void)Result;
4818 continue;
4819 }
4820
4821 // Multiple matches; we can't resolve to a single declaration.
4822 if (Matched)
4823 return 0;
4824
4825 Matched = Specialization;
4826 }
4827
4828 return Matched;
4829}
4830
Douglas Gregorcabea402009-09-22 15:41:20 +00004831/// \brief Add a single candidate to the overload set.
4832static void AddOverloadedCallCandidate(Sema &S,
John McCalld14a8642009-11-21 08:51:07 +00004833 NamedDecl *Callee,
John McCall6b51f282009-11-23 01:53:49 +00004834 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004835 Expr **Args, unsigned NumArgs,
4836 OverloadCandidateSet &CandidateSet,
4837 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00004838 if (isa<UsingShadowDecl>(Callee))
4839 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
4840
Douglas Gregorcabea402009-09-22 15:41:20 +00004841 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00004842 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregorcabea402009-09-22 15:41:20 +00004843 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4844 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004845 return;
John McCalld14a8642009-11-21 08:51:07 +00004846 }
4847
4848 if (FunctionTemplateDecl *FuncTemplate
4849 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00004850 S.AddTemplateOverloadCandidate(FuncTemplate, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00004851 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00004852 return;
4853 }
4854
4855 assert(false && "unhandled case in overloaded call candidate");
4856
4857 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00004858}
4859
4860/// \brief Add the overload candidates named by callee and/or found by argument
4861/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00004862void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00004863 Expr **Args, unsigned NumArgs,
4864 OverloadCandidateSet &CandidateSet,
4865 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00004866
4867#ifndef NDEBUG
4868 // Verify that ArgumentDependentLookup is consistent with the rules
4869 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00004870 //
Douglas Gregorcabea402009-09-22 15:41:20 +00004871 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4872 // and let Y be the lookup set produced by argument dependent
4873 // lookup (defined as follows). If X contains
4874 //
4875 // -- a declaration of a class member, or
4876 //
4877 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00004878 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00004879 //
4880 // -- a declaration that is neither a function or a function
4881 // template
4882 //
4883 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00004884
John McCall57500772009-12-16 12:17:52 +00004885 if (ULE->requiresADL()) {
4886 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
4887 E = ULE->decls_end(); I != E; ++I) {
4888 assert(!(*I)->getDeclContext()->isRecord());
4889 assert(isa<UsingShadowDecl>(*I) ||
4890 !(*I)->getDeclContext()->isFunctionOrMethod());
4891 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00004892 }
4893 }
4894#endif
4895
John McCall57500772009-12-16 12:17:52 +00004896 // It would be nice to avoid this copy.
4897 TemplateArgumentListInfo TABuffer;
4898 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
4899 if (ULE->hasExplicitTemplateArgs()) {
4900 ULE->copyTemplateArgumentsInto(TABuffer);
4901 ExplicitTemplateArgs = &TABuffer;
4902 }
4903
4904 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
4905 E = ULE->decls_end(); I != E; ++I)
John McCall6b51f282009-11-23 01:53:49 +00004906 AddOverloadedCallCandidate(*this, *I, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00004907 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00004908 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00004909
John McCall57500772009-12-16 12:17:52 +00004910 if (ULE->requiresADL())
4911 AddArgumentDependentLookupCandidates(ULE->getName(), Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004912 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004913 CandidateSet,
4914 PartialOverloading);
4915}
John McCalld681c392009-12-16 08:11:27 +00004916
John McCall57500772009-12-16 12:17:52 +00004917static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
4918 Expr **Args, unsigned NumArgs) {
4919 Fn->Destroy(SemaRef.Context);
4920 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4921 Args[Arg]->Destroy(SemaRef.Context);
4922 return SemaRef.ExprError();
4923}
4924
John McCalld681c392009-12-16 08:11:27 +00004925/// Attempts to recover from a call where no functions were found.
4926///
4927/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00004928static Sema::OwningExprResult
4929BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn,
4930 UnresolvedLookupExpr *ULE,
4931 SourceLocation LParenLoc,
4932 Expr **Args, unsigned NumArgs,
4933 SourceLocation *CommaLocs,
4934 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00004935
4936 CXXScopeSpec SS;
4937 if (ULE->getQualifier()) {
4938 SS.setScopeRep(ULE->getQualifier());
4939 SS.setRange(ULE->getQualifierRange());
4940 }
4941
John McCall57500772009-12-16 12:17:52 +00004942 TemplateArgumentListInfo TABuffer;
4943 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
4944 if (ULE->hasExplicitTemplateArgs()) {
4945 ULE->copyTemplateArgumentsInto(TABuffer);
4946 ExplicitTemplateArgs = &TABuffer;
4947 }
4948
John McCalld681c392009-12-16 08:11:27 +00004949 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
4950 Sema::LookupOrdinaryName);
Douglas Gregor598b08f2009-12-31 05:20:13 +00004951 if (SemaRef.DiagnoseEmptyLookup(/*Scope=*/0, SS, R))
John McCall57500772009-12-16 12:17:52 +00004952 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00004953
John McCall57500772009-12-16 12:17:52 +00004954 assert(!R.empty() && "lookup results empty despite recovery");
4955
4956 // Build an implicit member call if appropriate. Just drop the
4957 // casts and such from the call, we don't really care.
4958 Sema::OwningExprResult NewFn = SemaRef.ExprError();
4959 if ((*R.begin())->isCXXClassMember())
4960 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
4961 else if (ExplicitTemplateArgs)
4962 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
4963 else
4964 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
4965
4966 if (NewFn.isInvalid())
4967 return Destroy(SemaRef, Fn, Args, NumArgs);
4968
4969 Fn->Destroy(SemaRef.Context);
4970
4971 // This shouldn't cause an infinite loop because we're giving it
4972 // an expression with non-empty lookup results, which should never
4973 // end up here.
4974 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
4975 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
4976 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00004977}
Douglas Gregorcabea402009-09-22 15:41:20 +00004978
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004979/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00004980/// (which eventually refers to the declaration Func) and the call
4981/// arguments Args/NumArgs, attempt to resolve the function call down
4982/// to a specific function. If overload resolution succeeds, returns
4983/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00004984/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004985/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00004986Sema::OwningExprResult
4987Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE,
4988 SourceLocation LParenLoc,
4989 Expr **Args, unsigned NumArgs,
4990 SourceLocation *CommaLocs,
4991 SourceLocation RParenLoc) {
4992#ifndef NDEBUG
4993 if (ULE->requiresADL()) {
4994 // To do ADL, we must have found an unqualified name.
4995 assert(!ULE->getQualifier() && "qualified name with ADL");
4996
4997 // We don't perform ADL for implicit declarations of builtins.
4998 // Verify that this was correctly set up.
4999 FunctionDecl *F;
5000 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5001 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5002 F->getBuiltinID() && F->isImplicit())
5003 assert(0 && "performing ADL for builtin");
5004
5005 // We don't perform ADL in C.
5006 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5007 }
5008#endif
5009
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005010 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005011
John McCall57500772009-12-16 12:17:52 +00005012 // Add the functions denoted by the callee to the set of candidate
5013 // functions, including those from argument-dependent lookup.
5014 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00005015
5016 // If we found nothing, try to recover.
5017 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5018 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00005019 if (CandidateSet.empty())
5020 return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs,
5021 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005022
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005023 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005024 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00005025 case OR_Success: {
5026 FunctionDecl *FDecl = Best->Function;
5027 Fn = FixOverloadedFunctionReference(Fn, FDecl);
5028 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5029 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005030
5031 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00005032 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005033 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00005034 << ULE->getName() << Fn->getSourceRange();
John McCall12f97bc2010-01-08 04:41:39 +00005035 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005036 break;
5037
5038 case OR_Ambiguous:
5039 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00005040 << ULE->getName() << Fn->getSourceRange();
John McCall12f97bc2010-01-08 04:41:39 +00005041 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005042 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005043
5044 case OR_Deleted:
5045 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5046 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00005047 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00005048 << Fn->getSourceRange();
John McCall12f97bc2010-01-08 04:41:39 +00005049 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005050 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005051 }
5052
5053 // Overload resolution failed. Destroy all of the subexpressions and
5054 // return NULL.
5055 Fn->Destroy(Context);
5056 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5057 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00005058 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005059}
5060
John McCall283b9012009-11-22 00:44:51 +00005061static bool IsOverloaded(const Sema::FunctionSet &Functions) {
5062 return Functions.size() > 1 ||
5063 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5064}
5065
Douglas Gregor084d8552009-03-13 23:49:33 +00005066/// \brief Create a unary operation that may resolve to an overloaded
5067/// operator.
5068///
5069/// \param OpLoc The location of the operator itself (e.g., '*').
5070///
5071/// \param OpcIn The UnaryOperator::Opcode that describes this
5072/// operator.
5073///
5074/// \param Functions The set of non-member functions that will be
5075/// considered by overload resolution. The caller needs to build this
5076/// set based on the context using, e.g.,
5077/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5078/// set should not contain any member functions; those will be added
5079/// by CreateOverloadedUnaryOp().
5080///
5081/// \param input The input argument.
5082Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
5083 unsigned OpcIn,
5084 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00005085 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005086 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5087 Expr *Input = (Expr *)input.get();
5088
5089 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5090 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5091 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5092
5093 Expr *Args[2] = { Input, 0 };
5094 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00005095
Douglas Gregor084d8552009-03-13 23:49:33 +00005096 // For post-increment and post-decrement, add the implicit '0' as
5097 // the second argument, so that we know this is a post-increment or
5098 // post-decrement.
5099 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5100 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00005101 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00005102 SourceLocation());
5103 NumArgs = 2;
5104 }
5105
5106 if (Input->isTypeDependent()) {
John McCalld14a8642009-11-21 08:51:07 +00005107 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005108 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5109 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00005110 /*ADL*/ true, IsOverloaded(Functions));
Mike Stump11289f42009-09-09 15:08:12 +00005111 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00005112 FuncEnd = Functions.end();
5113 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00005114 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00005115
Douglas Gregor084d8552009-03-13 23:49:33 +00005116 input.release();
5117 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5118 &Args[0], NumArgs,
5119 Context.DependentTy,
5120 OpLoc));
5121 }
5122
5123 // Build an empty overload set.
5124 OverloadCandidateSet CandidateSet;
5125
5126 // Add the candidates from the given function set.
5127 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
5128
5129 // Add operator candidates that are member functions.
5130 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5131
5132 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005133 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00005134
5135 // Perform overload resolution.
5136 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005137 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005138 case OR_Success: {
5139 // We found a built-in operator or an overloaded operator.
5140 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00005141
Douglas Gregor084d8552009-03-13 23:49:33 +00005142 if (FnDecl) {
5143 // We matched an overloaded operator. Build a call to that
5144 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00005145
Douglas Gregor084d8552009-03-13 23:49:33 +00005146 // Convert the arguments.
5147 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
5148 if (PerformObjectArgumentInitialization(Input, Method))
5149 return ExprError();
5150 } else {
5151 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00005152 OwningExprResult InputInit
5153 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005154 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00005155 SourceLocation(),
5156 move(input));
5157 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00005158 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005159
Douglas Gregore6600372009-12-23 17:40:29 +00005160 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005161 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00005162 }
5163
5164 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005165 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005166
Douglas Gregor084d8552009-03-13 23:49:33 +00005167 // Build the actual expression node.
5168 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5169 SourceLocation());
5170 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005171
Douglas Gregor084d8552009-03-13 23:49:33 +00005172 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00005173 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005174 ExprOwningPtr<CallExpr> TheCall(this,
5175 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00005176 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005177
5178 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5179 FnDecl))
5180 return ExprError();
5181
5182 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00005183 } else {
5184 // We matched a built-in operator. Convert the arguments, then
5185 // break out so that we will build the appropriate built-in
5186 // operator node.
5187 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005188 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00005189 return ExprError();
5190
5191 break;
5192 }
5193 }
5194
5195 case OR_No_Viable_Function:
5196 // No viable function; fall through to handling this as a
5197 // built-in operator, which will produce an error message for us.
5198 break;
5199
5200 case OR_Ambiguous:
5201 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5202 << UnaryOperator::getOpcodeStr(Opc)
5203 << Input->getSourceRange();
John McCall12f97bc2010-01-08 04:41:39 +00005204 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005205 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005206 return ExprError();
5207
5208 case OR_Deleted:
5209 Diag(OpLoc, diag::err_ovl_deleted_oper)
5210 << Best->Function->isDeleted()
5211 << UnaryOperator::getOpcodeStr(Opc)
5212 << Input->getSourceRange();
John McCall12f97bc2010-01-08 04:41:39 +00005213 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Douglas Gregor084d8552009-03-13 23:49:33 +00005214 return ExprError();
5215 }
5216
5217 // Either we found no viable overloaded operator or we matched a
5218 // built-in operator. In either case, fall through to trying to
5219 // build a built-in operation.
5220 input.release();
5221 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5222}
5223
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005224/// \brief Create a binary operation that may resolve to an overloaded
5225/// operator.
5226///
5227/// \param OpLoc The location of the operator itself (e.g., '+').
5228///
5229/// \param OpcIn The BinaryOperator::Opcode that describes this
5230/// operator.
5231///
5232/// \param Functions The set of non-member functions that will be
5233/// considered by overload resolution. The caller needs to build this
5234/// set based on the context using, e.g.,
5235/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5236/// set should not contain any member functions; those will be added
5237/// by CreateOverloadedBinOp().
5238///
5239/// \param LHS Left-hand argument.
5240/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00005241Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005242Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005243 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005244 FunctionSet &Functions,
5245 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005246 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00005247 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005248
5249 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5250 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5251 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5252
5253 // If either side is type-dependent, create an appropriate dependent
5254 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00005255 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00005256 if (Functions.empty()) {
5257 // If there are no functions to store, just build a dependent
5258 // BinaryOperator or CompoundAssignment.
5259 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5260 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5261 Context.DependentTy, OpLoc));
5262
5263 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5264 Context.DependentTy,
5265 Context.DependentTy,
5266 Context.DependentTy,
5267 OpLoc));
5268 }
5269
John McCalld14a8642009-11-21 08:51:07 +00005270 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005271 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5272 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00005273 /* ADL */ true, IsOverloaded(Functions));
John McCalld14a8642009-11-21 08:51:07 +00005274
Mike Stump11289f42009-09-09 15:08:12 +00005275 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005276 FuncEnd = Functions.end();
5277 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00005278 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00005279
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005280 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00005281 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005282 Context.DependentTy,
5283 OpLoc));
5284 }
5285
5286 // If this is the .* operator, which is not overloadable, just
5287 // create a built-in binary operator.
5288 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00005289 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005290
Sebastian Redl6a96bf72009-11-18 23:10:33 +00005291 // If this is the assignment operator, we only perform overload resolution
5292 // if the left-hand side is a class or enumeration type. This is actually
5293 // a hack. The standard requires that we do overload resolution between the
5294 // various built-in candidates, but as DR507 points out, this can lead to
5295 // problems. So we do it this way, which pretty much follows what GCC does.
5296 // Note that we go the traditional code path for compound assignment forms.
5297 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00005298 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005299
Douglas Gregor084d8552009-03-13 23:49:33 +00005300 // Build an empty overload set.
5301 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005302
5303 // Add the candidates from the given function set.
5304 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
5305
5306 // Add operator candidates that are member functions.
5307 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5308
5309 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005310 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005311
5312 // Perform overload resolution.
5313 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005314 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005315 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005316 // We found a built-in operator or an overloaded operator.
5317 FunctionDecl *FnDecl = Best->Function;
5318
5319 if (FnDecl) {
5320 // We matched an overloaded operator. Build a call to that
5321 // operator.
5322
5323 // Convert the arguments.
5324 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005325 OwningExprResult Arg1
5326 = PerformCopyInitialization(
5327 InitializedEntity::InitializeParameter(
5328 FnDecl->getParamDecl(0)),
5329 SourceLocation(),
5330 Owned(Args[1]));
5331 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005332 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005333
5334 if (PerformObjectArgumentInitialization(Args[0], Method))
5335 return ExprError();
5336
5337 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005338 } else {
5339 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005340 OwningExprResult Arg0
5341 = PerformCopyInitialization(
5342 InitializedEntity::InitializeParameter(
5343 FnDecl->getParamDecl(0)),
5344 SourceLocation(),
5345 Owned(Args[0]));
5346 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005347 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005348
5349 OwningExprResult Arg1
5350 = PerformCopyInitialization(
5351 InitializedEntity::InitializeParameter(
5352 FnDecl->getParamDecl(1)),
5353 SourceLocation(),
5354 Owned(Args[1]));
5355 if (Arg1.isInvalid())
5356 return ExprError();
5357 Args[0] = LHS = Arg0.takeAs<Expr>();
5358 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005359 }
5360
5361 // Determine the result type
5362 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00005363 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005364 ResultTy = ResultTy.getNonReferenceType();
5365
5366 // Build the actual expression node.
5367 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00005368 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005369 UsualUnaryConversions(FnExpr);
5370
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005371 ExprOwningPtr<CXXOperatorCallExpr>
5372 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5373 Args, 2, ResultTy,
5374 OpLoc));
5375
5376 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5377 FnDecl))
5378 return ExprError();
5379
5380 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005381 } else {
5382 // We matched a built-in operator. Convert the arguments, then
5383 // break out so that we will build the appropriate built-in
5384 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00005385 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005386 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00005387 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005388 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005389 return ExprError();
5390
5391 break;
5392 }
5393 }
5394
Douglas Gregor66950a32009-09-30 21:46:01 +00005395 case OR_No_Viable_Function: {
5396 // C++ [over.match.oper]p9:
5397 // If the operator is the operator , [...] and there are no
5398 // viable functions, then the operator is assumed to be the
5399 // built-in operator and interpreted according to clause 5.
5400 if (Opc == BinaryOperator::Comma)
5401 break;
5402
Sebastian Redl027de2a2009-05-21 11:50:50 +00005403 // For class as left operand for assignment or compound assigment operator
5404 // do not fall through to handling in built-in, but report that no overloaded
5405 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00005406 OwningExprResult Result = ExprError();
5407 if (Args[0]->getType()->isRecordType() &&
5408 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00005409 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5410 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005411 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00005412 } else {
5413 // No viable function; try to create a built-in operation, which will
5414 // produce an error. Then, show the non-viable candidates.
5415 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00005416 }
Douglas Gregor66950a32009-09-30 21:46:01 +00005417 assert(Result.isInvalid() &&
5418 "C++ binary operator overloading is missing candidates!");
5419 if (Result.isInvalid())
John McCall12f97bc2010-01-08 04:41:39 +00005420 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005421 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00005422 return move(Result);
5423 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005424
5425 case OR_Ambiguous:
5426 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5427 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005428 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall12f97bc2010-01-08 04:41:39 +00005429 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005430 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005431 return ExprError();
5432
5433 case OR_Deleted:
5434 Diag(OpLoc, diag::err_ovl_deleted_oper)
5435 << Best->Function->isDeleted()
5436 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005437 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall12f97bc2010-01-08 04:41:39 +00005438 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005439 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00005440 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005441
Douglas Gregor66950a32009-09-30 21:46:01 +00005442 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00005443 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005444}
5445
Sebastian Redladba46e2009-10-29 20:17:01 +00005446Action::OwningExprResult
5447Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5448 SourceLocation RLoc,
5449 ExprArg Base, ExprArg Idx) {
5450 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5451 static_cast<Expr*>(Idx.get()) };
5452 DeclarationName OpName =
5453 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5454
5455 // If either side is type-dependent, create an appropriate dependent
5456 // expression.
5457 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5458
John McCalld14a8642009-11-21 08:51:07 +00005459 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005460 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5461 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00005462 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00005463 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00005464
5465 Base.release();
5466 Idx.release();
5467 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5468 Args, 2,
5469 Context.DependentTy,
5470 RLoc));
5471 }
5472
5473 // Build an empty overload set.
5474 OverloadCandidateSet CandidateSet;
5475
5476 // Subscript can only be overloaded as a member function.
5477
5478 // Add operator candidates that are member functions.
5479 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5480
5481 // Add builtin operator candidates.
5482 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5483
5484 // Perform overload resolution.
5485 OverloadCandidateSet::iterator Best;
5486 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5487 case OR_Success: {
5488 // We found a built-in operator or an overloaded operator.
5489 FunctionDecl *FnDecl = Best->Function;
5490
5491 if (FnDecl) {
5492 // We matched an overloaded operator. Build a call to that
5493 // operator.
5494
5495 // Convert the arguments.
5496 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5497 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5498 PerformCopyInitialization(Args[1],
5499 FnDecl->getParamDecl(0)->getType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005500 AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00005501 return ExprError();
5502
5503 // Determine the result type
5504 QualType ResultTy
5505 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5506 ResultTy = ResultTy.getNonReferenceType();
5507
5508 // Build the actual expression node.
5509 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5510 LLoc);
5511 UsualUnaryConversions(FnExpr);
5512
5513 Base.release();
5514 Idx.release();
5515 ExprOwningPtr<CXXOperatorCallExpr>
5516 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5517 FnExpr, Args, 2,
5518 ResultTy, RLoc));
5519
5520 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5521 FnDecl))
5522 return ExprError();
5523
5524 return MaybeBindToTemporary(TheCall.release());
5525 } else {
5526 // We matched a built-in operator. Convert the arguments, then
5527 // break out so that we will build the appropriate built-in
5528 // operator node.
5529 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005530 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00005531 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005532 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00005533 return ExprError();
5534
5535 break;
5536 }
5537 }
5538
5539 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00005540 if (CandidateSet.empty())
5541 Diag(LLoc, diag::err_ovl_no_oper)
5542 << Args[0]->getType() << /*subscript*/ 0
5543 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5544 else
5545 Diag(LLoc, diag::err_ovl_no_viable_subscript)
5546 << Args[0]->getType()
5547 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall12f97bc2010-01-08 04:41:39 +00005548 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates,
John McCall02374852010-01-07 02:04:15 +00005549 "[]", LLoc);
5550 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00005551 }
5552
5553 case OR_Ambiguous:
5554 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5555 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall12f97bc2010-01-08 04:41:39 +00005556 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates,
Sebastian Redladba46e2009-10-29 20:17:01 +00005557 "[]", LLoc);
5558 return ExprError();
5559
5560 case OR_Deleted:
5561 Diag(LLoc, diag::err_ovl_deleted_oper)
5562 << Best->Function->isDeleted() << "[]"
5563 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall12f97bc2010-01-08 04:41:39 +00005564 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates,
5565 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00005566 return ExprError();
5567 }
5568
5569 // We matched a built-in operator; build it.
5570 Base.release();
5571 Idx.release();
5572 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5573 Owned(Args[1]), RLoc);
5574}
5575
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005576/// BuildCallToMemberFunction - Build a call to a member
5577/// function. MemExpr is the expression that refers to the member
5578/// function (and includes the object parameter), Args/NumArgs are the
5579/// arguments to the function call (not including the object
5580/// parameter). The caller needs to validate that the member
5581/// expression refers to a member function or an overloaded member
5582/// function.
John McCall2d74de92009-12-01 22:10:20 +00005583Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00005584Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5585 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005586 unsigned NumArgs, SourceLocation *CommaLocs,
5587 SourceLocation RParenLoc) {
5588 // Dig out the member expression. This holds both the object
5589 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00005590 Expr *NakedMemExpr = MemExprE->IgnoreParens();
5591
John McCall10eae182009-11-30 22:42:35 +00005592 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005593 CXXMethodDecl *Method = 0;
John McCall10eae182009-11-30 22:42:35 +00005594 if (isa<MemberExpr>(NakedMemExpr)) {
5595 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00005596 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5597 } else {
5598 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
John McCall2d74de92009-12-01 22:10:20 +00005599
John McCall6e9f8f62009-12-03 04:06:58 +00005600 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00005601
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005602 // Add overload candidates
5603 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00005604
John McCall2d74de92009-12-01 22:10:20 +00005605 // FIXME: avoid copy.
5606 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5607 if (UnresExpr->hasExplicitTemplateArgs()) {
5608 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5609 TemplateArgs = &TemplateArgsBuffer;
5610 }
5611
John McCall10eae182009-11-30 22:42:35 +00005612 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
5613 E = UnresExpr->decls_end(); I != E; ++I) {
5614
John McCall6e9f8f62009-12-03 04:06:58 +00005615 NamedDecl *Func = *I;
5616 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
5617 if (isa<UsingShadowDecl>(Func))
5618 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
5619
John McCall10eae182009-11-30 22:42:35 +00005620 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00005621 // If explicit template arguments were provided, we can't call a
5622 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00005623 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00005624 continue;
5625
John McCall6e9f8f62009-12-03 04:06:58 +00005626 AddMethodCandidate(Method, ActingDC, ObjectType, Args, NumArgs,
5627 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005628 } else {
John McCall10eae182009-11-30 22:42:35 +00005629 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall6e9f8f62009-12-03 04:06:58 +00005630 ActingDC, TemplateArgs,
5631 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005632 CandidateSet,
5633 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005634 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005635 }
Mike Stump11289f42009-09-09 15:08:12 +00005636
John McCall10eae182009-11-30 22:42:35 +00005637 DeclarationName DeclName = UnresExpr->getMemberName();
5638
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005639 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00005640 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005641 case OR_Success:
5642 Method = cast<CXXMethodDecl>(Best->Function);
5643 break;
5644
5645 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00005646 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005647 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005648 << DeclName << MemExprE->getSourceRange();
John McCall12f97bc2010-01-08 04:41:39 +00005649 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005650 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005651 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005652
5653 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00005654 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005655 << DeclName << MemExprE->getSourceRange();
John McCall12f97bc2010-01-08 04:41:39 +00005656 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005657 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005658 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005659
5660 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00005661 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00005662 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00005663 << DeclName << MemExprE->getSourceRange();
John McCall12f97bc2010-01-08 04:41:39 +00005664 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005665 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005666 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005667 }
5668
Douglas Gregor51c538b2009-11-20 19:42:02 +00005669 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCall2d74de92009-12-01 22:10:20 +00005670
John McCall2d74de92009-12-01 22:10:20 +00005671 // If overload resolution picked a static member, build a
5672 // non-member call based on that function.
5673 if (Method->isStatic()) {
5674 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
5675 Args, NumArgs, RParenLoc);
5676 }
5677
John McCall10eae182009-11-30 22:42:35 +00005678 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005679 }
5680
5681 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00005682 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00005683 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00005684 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005685 Method->getResultType().getNonReferenceType(),
5686 RParenLoc));
5687
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005688 // Check for a valid return type.
5689 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5690 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00005691 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005692
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005693 // Convert the object argument (for a non-static member function call).
John McCall2d74de92009-12-01 22:10:20 +00005694 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00005695 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005696 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCall2d74de92009-12-01 22:10:20 +00005697 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005698 MemExpr->setBase(ObjectArg);
5699
5700 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005701 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00005702 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005703 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00005704 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005705
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005706 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00005707 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00005708
John McCall2d74de92009-12-01 22:10:20 +00005709 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005710}
5711
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005712/// BuildCallToObjectOfClassType - Build a call to an object of class
5713/// type (C++ [over.call.object]), which can end up invoking an
5714/// overloaded function call operator (@c operator()) or performing a
5715/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00005716Sema::ExprResult
5717Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00005718 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005719 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00005720 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005721 SourceLocation RParenLoc) {
5722 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005723 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00005724
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005725 // C++ [over.call.object]p1:
5726 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00005727 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005728 // candidate functions includes at least the function call
5729 // operators of T. The function call operators of T are obtained by
5730 // ordinary lookup of the name operator() in the context of
5731 // (E).operator().
5732 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00005733 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005734
5735 if (RequireCompleteType(LParenLoc, Object->getType(),
5736 PartialDiagnostic(diag::err_incomplete_object_call)
5737 << Object->getSourceRange()))
5738 return true;
5739
John McCall27b18f82009-11-17 02:14:36 +00005740 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5741 LookupQualifiedName(R, Record->getDecl());
5742 R.suppressDiagnostics();
5743
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005744 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00005745 Oper != OperEnd; ++Oper) {
John McCall6e9f8f62009-12-03 04:06:58 +00005746 AddMethodCandidate(*Oper, Object->getType(), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005747 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00005748 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005749
Douglas Gregorab7897a2008-11-19 22:57:39 +00005750 // C++ [over.call.object]p2:
5751 // In addition, for each conversion function declared in T of the
5752 // form
5753 //
5754 // operator conversion-type-id () cv-qualifier;
5755 //
5756 // where cv-qualifier is the same cv-qualification as, or a
5757 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00005758 // denotes the type "pointer to function of (P1,...,Pn) returning
5759 // R", or the type "reference to pointer to function of
5760 // (P1,...,Pn) returning R", or the type "reference to function
5761 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00005762 // is also considered as a candidate function. Similarly,
5763 // surrogate call functions are added to the set of candidate
5764 // functions for each conversion function declared in an
5765 // accessible base class provided the function is not hidden
5766 // within T by another intervening declaration.
John McCalld14a8642009-11-21 08:51:07 +00005767 const UnresolvedSet *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00005768 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00005769 for (UnresolvedSet::iterator I = Conversions->begin(),
5770 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00005771 NamedDecl *D = *I;
5772 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5773 if (isa<UsingShadowDecl>(D))
5774 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5775
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005776 // Skip over templated conversion functions; they aren't
5777 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00005778 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005779 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005780
John McCall6e9f8f62009-12-03 04:06:58 +00005781 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00005782
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005783 // Strip the reference type (if any) and then the pointer type (if
5784 // any) to get down to what might be a function type.
5785 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5786 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5787 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005788
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005789 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall6e9f8f62009-12-03 04:06:58 +00005790 AddSurrogateCandidate(Conv, ActingContext, Proto,
5791 Object->getType(), Args, NumArgs,
5792 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00005793 }
Mike Stump11289f42009-09-09 15:08:12 +00005794
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005795 // Perform overload resolution.
5796 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005797 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005798 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00005799 // Overload resolution succeeded; we'll build the appropriate call
5800 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005801 break;
5802
5803 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00005804 if (CandidateSet.empty())
5805 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
5806 << Object->getType() << /*call*/ 1
5807 << Object->getSourceRange();
5808 else
5809 Diag(Object->getSourceRange().getBegin(),
5810 diag::err_ovl_no_viable_object_call)
5811 << Object->getType() << Object->getSourceRange();
John McCall12f97bc2010-01-08 04:41:39 +00005812 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005813 break;
5814
5815 case OR_Ambiguous:
5816 Diag(Object->getSourceRange().getBegin(),
5817 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005818 << Object->getType() << Object->getSourceRange();
John McCall12f97bc2010-01-08 04:41:39 +00005819 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005820 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005821
5822 case OR_Deleted:
5823 Diag(Object->getSourceRange().getBegin(),
5824 diag::err_ovl_deleted_object_call)
5825 << Best->Function->isDeleted()
5826 << Object->getType() << Object->getSourceRange();
John McCall12f97bc2010-01-08 04:41:39 +00005827 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005828 break;
Mike Stump11289f42009-09-09 15:08:12 +00005829 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005830
Douglas Gregorab7897a2008-11-19 22:57:39 +00005831 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005832 // We had an error; delete all of the subexpressions and return
5833 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00005834 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005835 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00005836 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005837 return true;
5838 }
5839
Douglas Gregorab7897a2008-11-19 22:57:39 +00005840 if (Best->Function == 0) {
5841 // Since there is no function declaration, this is one of the
5842 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00005843 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00005844 = cast<CXXConversionDecl>(
5845 Best->Conversions[0].UserDefined.ConversionFunction);
5846
5847 // We selected one of the surrogate functions that converts the
5848 // object parameter to a function pointer. Perform the conversion
5849 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005850
5851 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005852 // and then call it.
Eli Friedmana958a012009-12-09 04:52:43 +00005853 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005854
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005855 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005856 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5857 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005858 }
5859
5860 // We found an overloaded operator(). Build a CXXOperatorCallExpr
5861 // that calls this method, using Object for the implicit object
5862 // parameter and passing along the remaining arguments.
5863 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00005864 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005865
5866 unsigned NumArgsInProto = Proto->getNumArgs();
5867 unsigned NumArgsToCheck = NumArgs;
5868
5869 // Build the full argument list for the method call (the
5870 // implicit object parameter is placed at the beginning of the
5871 // list).
5872 Expr **MethodArgs;
5873 if (NumArgs < NumArgsInProto) {
5874 NumArgsToCheck = NumArgsInProto;
5875 MethodArgs = new Expr*[NumArgsInProto + 1];
5876 } else {
5877 MethodArgs = new Expr*[NumArgs + 1];
5878 }
5879 MethodArgs[0] = Object;
5880 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5881 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00005882
5883 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00005884 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005885 UsualUnaryConversions(NewFn);
5886
5887 // Once we've built TheCall, all of the expressions are properly
5888 // owned.
5889 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005890 ExprOwningPtr<CXXOperatorCallExpr>
5891 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005892 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00005893 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005894 delete [] MethodArgs;
5895
Anders Carlsson3d5829c2009-10-13 21:49:31 +00005896 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5897 Method))
5898 return true;
5899
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005900 // We may have default arguments. If so, we need to allocate more
5901 // slots in the call for them.
5902 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00005903 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005904 else if (NumArgs > NumArgsInProto)
5905 NumArgsToCheck = NumArgsInProto;
5906
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005907 bool IsError = false;
5908
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005909 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005910 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005911 TheCall->setArg(0, Object);
5912
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005913
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005914 // Check the argument types.
5915 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005916 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005917 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005918 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00005919
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005920 // Pass the argument.
5921 QualType ProtoArgType = Proto->getArgType(i);
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005922 IsError |= PerformCopyInitialization(Arg, ProtoArgType, AA_Passing);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005923 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00005924 OwningExprResult DefArg
5925 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
5926 if (DefArg.isInvalid()) {
5927 IsError = true;
5928 break;
5929 }
5930
5931 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005932 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005933
5934 TheCall->setArg(i + 1, Arg);
5935 }
5936
5937 // If this is a variadic call, handle args passed through "...".
5938 if (Proto->isVariadic()) {
5939 // Promote the arguments (C99 6.5.2.2p7).
5940 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5941 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005942 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005943 TheCall->setArg(i + 1, Arg);
5944 }
5945 }
5946
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005947 if (IsError) return true;
5948
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005949 if (CheckFunctionCall(Method, TheCall.get()))
5950 return true;
5951
Anders Carlsson1c83deb2009-08-16 03:53:54 +00005952 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005953}
5954
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005955/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00005956/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005957/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00005958Sema::OwningExprResult
5959Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5960 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005961 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00005962
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005963 // C++ [over.ref]p1:
5964 //
5965 // [...] An expression x->m is interpreted as (x.operator->())->m
5966 // for a class object x of type T if T::operator->() exists and if
5967 // the operator is selected as the best match function by the
5968 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005969 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5970 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005971 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00005972
Eli Friedman132e70b2009-11-18 01:28:03 +00005973 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
5974 PDiag(diag::err_typecheck_incomplete_tag)
5975 << Base->getSourceRange()))
5976 return ExprError();
5977
John McCall27b18f82009-11-17 02:14:36 +00005978 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
5979 LookupQualifiedName(R, BaseRecord->getDecl());
5980 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00005981
5982 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00005983 Oper != OperEnd; ++Oper) {
5984 NamedDecl *D = *Oper;
5985 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5986 if (isa<UsingShadowDecl>(D))
5987 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5988
5989 AddMethodCandidate(cast<CXXMethodDecl>(D), ActingContext,
5990 Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005991 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00005992 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005993
5994 // Perform overload resolution.
5995 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005996 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005997 case OR_Success:
5998 // Overload resolution succeeded; we'll build the call below.
5999 break;
6000
6001 case OR_No_Viable_Function:
6002 if (CandidateSet.empty())
6003 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00006004 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006005 else
6006 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00006007 << "operator->" << Base->getSourceRange();
John McCall12f97bc2010-01-08 04:41:39 +00006008 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Douglas Gregord8061562009-08-06 03:17:00 +00006009 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006010
6011 case OR_Ambiguous:
6012 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00006013 << "->" << Base->getSourceRange();
John McCall12f97bc2010-01-08 04:41:39 +00006014 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates);
Douglas Gregord8061562009-08-06 03:17:00 +00006015 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006016
6017 case OR_Deleted:
6018 Diag(OpLoc, diag::err_ovl_deleted_oper)
6019 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00006020 << "->" << Base->getSourceRange();
John McCall12f97bc2010-01-08 04:41:39 +00006021 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates);
Douglas Gregord8061562009-08-06 03:17:00 +00006022 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006023 }
6024
6025 // Convert the object parameter.
6026 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00006027 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00006028 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00006029
6030 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00006031 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006032
6033 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00006034 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6035 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006036 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006037
6038 QualType ResultTy = Method->getResultType().getNonReferenceType();
6039 ExprOwningPtr<CXXOperatorCallExpr>
6040 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6041 &Base, 1, ResultTy, OpLoc));
6042
6043 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6044 Method))
6045 return ExprError();
6046 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006047}
6048
Douglas Gregorcd695e52008-11-10 20:40:00 +00006049/// FixOverloadedFunctionReference - E is an expression that refers to
6050/// a C++ overloaded function (possibly with some parentheses and
6051/// perhaps a '&' around it). We have resolved the overloaded function
6052/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006053/// refer (possibly indirectly) to Fn. Returns the new expr.
6054Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006055 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor51c538b2009-11-20 19:42:02 +00006056 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
6057 if (SubExpr == PE->getSubExpr())
6058 return PE->Retain();
6059
6060 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6061 }
6062
6063 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6064 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00006065 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00006066 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00006067 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00006068 if (SubExpr == ICE->getSubExpr())
6069 return ICE->Retain();
6070
6071 return new (Context) ImplicitCastExpr(ICE->getType(),
6072 ICE->getCastKind(),
6073 SubExpr,
6074 ICE->isLvalueCast());
6075 }
6076
6077 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00006078 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00006079 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006080 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6081 if (Method->isStatic()) {
6082 // Do nothing: static member functions aren't any different
6083 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00006084 } else {
John McCalle66edc12009-11-24 19:00:30 +00006085 // Fix the sub expression, which really has to be an
6086 // UnresolvedLookupExpr holding an overloaded member function
6087 // or template.
John McCalld14a8642009-11-21 08:51:07 +00006088 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6089 if (SubExpr == UnOp->getSubExpr())
6090 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00006091
John McCalld14a8642009-11-21 08:51:07 +00006092 assert(isa<DeclRefExpr>(SubExpr)
6093 && "fixed to something other than a decl ref");
6094 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6095 && "fixed to a member ref with no nested name qualifier");
6096
6097 // We have taken the address of a pointer to member
6098 // function. Perform the computation here so that we get the
6099 // appropriate pointer to member type.
6100 QualType ClassType
6101 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6102 QualType MemPtrType
6103 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6104
6105 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6106 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006107 }
6108 }
Douglas Gregor51c538b2009-11-20 19:42:02 +00006109 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6110 if (SubExpr == UnOp->getSubExpr())
6111 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006112
Douglas Gregor51c538b2009-11-20 19:42:02 +00006113 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6114 Context.getPointerType(SubExpr->getType()),
6115 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00006116 }
John McCalld14a8642009-11-21 08:51:07 +00006117
6118 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00006119 // FIXME: avoid copy.
6120 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00006121 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00006122 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6123 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00006124 }
6125
John McCalld14a8642009-11-21 08:51:07 +00006126 return DeclRefExpr::Create(Context,
6127 ULE->getQualifier(),
6128 ULE->getQualifierRange(),
6129 Fn,
6130 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006131 Fn->getType(),
6132 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00006133 }
6134
John McCall10eae182009-11-30 22:42:35 +00006135 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00006136 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00006137 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6138 if (MemExpr->hasExplicitTemplateArgs()) {
6139 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6140 TemplateArgs = &TemplateArgsBuffer;
6141 }
John McCall6b51f282009-11-23 01:53:49 +00006142
John McCall2d74de92009-12-01 22:10:20 +00006143 Expr *Base;
6144
6145 // If we're filling in
6146 if (MemExpr->isImplicitAccess()) {
6147 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6148 return DeclRefExpr::Create(Context,
6149 MemExpr->getQualifier(),
6150 MemExpr->getQualifierRange(),
6151 Fn,
6152 MemExpr->getMemberLoc(),
6153 Fn->getType(),
6154 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00006155 } else {
6156 SourceLocation Loc = MemExpr->getMemberLoc();
6157 if (MemExpr->getQualifier())
6158 Loc = MemExpr->getQualifierRange().getBegin();
6159 Base = new (Context) CXXThisExpr(Loc,
6160 MemExpr->getBaseType(),
6161 /*isImplicit=*/true);
6162 }
John McCall2d74de92009-12-01 22:10:20 +00006163 } else
6164 Base = MemExpr->getBase()->Retain();
6165
6166 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006167 MemExpr->isArrow(),
6168 MemExpr->getQualifier(),
6169 MemExpr->getQualifierRange(),
6170 Fn,
John McCall6b51f282009-11-23 01:53:49 +00006171 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006172 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006173 Fn->getType());
6174 }
6175
Douglas Gregor51c538b2009-11-20 19:42:02 +00006176 assert(false && "Invalid reference to overloaded function");
6177 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00006178}
6179
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006180Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
6181 FunctionDecl *Fn) {
6182 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
6183}
6184
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006185} // end namespace clang