blob: e4168eb7c8849bf1d476828f68e849fcb034c1e8 [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 McCall6a61b522010-01-13 09:16:55 +0000492 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall0d1da222010-01-12 00:44:57 +0000493 ICS.setBad();
John McCall6a61b522010-01-13 09:16:55 +0000494 ICS.Bad.init(BadConversionSequence::suppressed_user, From, ToType);
495 }
John McCalle8c8cd22010-01-13 22:30:33 +0000496 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000497 ICS.setAmbiguous();
498 ICS.Ambiguous.setFromType(From->getType());
499 ICS.Ambiguous.setToType(ToType);
500 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
501 Cand != Conversions.end(); ++Cand)
502 if (Cand->Viable)
503 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000504 } else {
John McCall0d1da222010-01-12 00:44:57 +0000505 ICS.setBad();
John McCall6a61b522010-01-13 09:16:55 +0000506 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000507 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000508
509 return ICS;
510}
511
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000512/// \brief Determine whether the conversion from FromType to ToType is a valid
513/// conversion that strips "noreturn" off the nested function type.
514static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
515 QualType ToType, QualType &ResultTy) {
516 if (Context.hasSameUnqualifiedType(FromType, ToType))
517 return false;
518
519 // Strip the noreturn off the type we're converting from; noreturn can
520 // safely be removed.
521 FromType = Context.getNoReturnType(FromType, false);
522 if (!Context.hasSameUnqualifiedType(FromType, ToType))
523 return false;
524
525 ResultTy = FromType;
526 return true;
527}
528
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000529/// IsStandardConversion - Determines whether there is a standard
530/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
531/// expression From to the type ToType. Standard conversion sequences
532/// only consider non-class types; for conversions that involve class
533/// types, use TryImplicitConversion. If a conversion exists, SCS will
534/// contain the standard conversion sequence required to perform this
535/// conversion and this routine will return true. Otherwise, this
536/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000537bool
538Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000539 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000540 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000541 QualType FromType = From->getType();
542
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000543 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000544 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000545 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000546 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000547 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000548 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000549
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000550 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000551 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000552 if (FromType->isRecordType() || ToType->isRecordType()) {
553 if (getLangOptions().CPlusPlus)
554 return false;
555
Mike Stump11289f42009-09-09 15:08:12 +0000556 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000557 }
558
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000559 // The first conversion can be an lvalue-to-rvalue conversion,
560 // array-to-pointer conversion, or function-to-pointer conversion
561 // (C++ 4p1).
562
Mike Stump11289f42009-09-09 15:08:12 +0000563 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000564 // An lvalue (3.10) of a non-function, non-array type T can be
565 // converted to an rvalue.
566 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000567 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000568 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000569 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000570 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000571
572 // If T is a non-class type, the type of the rvalue is the
573 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000574 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
575 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000576 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000577 } else if (FromType->isArrayType()) {
578 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000579 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000580
581 // An lvalue or rvalue of type "array of N T" or "array of unknown
582 // bound of T" can be converted to an rvalue of type "pointer to
583 // T" (C++ 4.2p1).
584 FromType = Context.getArrayDecayedType(FromType);
585
586 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
587 // This conversion is deprecated. (C++ D.4).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000588 SCS.Deprecated = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000589
590 // For the purpose of ranking in overload resolution
591 // (13.3.3.1.1), this conversion is considered an
592 // array-to-pointer conversion followed by a qualification
593 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000594 SCS.Second = ICK_Identity;
595 SCS.Third = ICK_Qualification;
John McCall0d1da222010-01-12 00:44:57 +0000596 SCS.setToType(ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000597 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000598 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000599 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
600 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000601 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000602
603 // An lvalue of function type T can be converted to an rvalue of
604 // type "pointer to T." The result is a pointer to the
605 // function. (C++ 4.3p1).
606 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000607 } else if (FunctionDecl *Fn
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000608 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000609 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000610 SCS.First = ICK_Function_To_Pointer;
611
612 // We were able to resolve the address of the overloaded function,
613 // so we can convert to the type of that function.
614 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000615 if (ToType->isLValueReferenceType())
616 FromType = Context.getLValueReferenceType(FromType);
617 else if (ToType->isRValueReferenceType())
618 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000619 else if (ToType->isMemberPointerType()) {
620 // Resolve address only succeeds if both sides are member pointers,
621 // but it doesn't have to be the same class. See DR 247.
622 // Note that this means that the type of &Derived::fn can be
623 // Ret (Base::*)(Args) if the fn overload actually found is from the
624 // base class, even if it was brought into the derived class via a
625 // using declaration. The standard isn't clear on this issue at all.
626 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
627 FromType = Context.getMemberPointerType(FromType,
628 Context.getTypeDeclType(M->getParent()).getTypePtr());
629 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000630 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000631 } else {
632 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000633 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000634 }
635
636 // The second conversion can be an integral promotion, floating
637 // point promotion, integral conversion, floating point conversion,
638 // floating-integral conversion, pointer conversion,
639 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000640 // For overloading in C, this can also be a "compatible-type"
641 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000642 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000643 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000644 // The unqualified versions of the types are the same: there's no
645 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000646 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000647 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000648 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000649 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000650 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000651 } else if (IsFloatingPointPromotion(FromType, ToType)) {
652 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000653 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000654 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000655 } else if (IsComplexPromotion(FromType, ToType)) {
656 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000657 SCS.Second = ICK_Complex_Promotion;
658 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000659 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000660 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000661 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000662 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000663 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000664 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
665 // Floating point conversions (C++ 4.8).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000666 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000667 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000668 } else if (FromType->isComplexType() && ToType->isComplexType()) {
669 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000670 SCS.Second = ICK_Complex_Conversion;
671 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000672 } else if ((FromType->isFloatingType() &&
673 ToType->isIntegralType() && (!ToType->isBooleanType() &&
674 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000675 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000676 ToType->isFloatingType())) {
677 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000678 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000679 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000680 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
681 (ToType->isComplexType() && FromType->isArithmeticType())) {
682 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000683 SCS.Second = ICK_Complex_Real;
684 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000685 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
686 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000687 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000688 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000689 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000690 } else if (IsMemberPointerConversion(From, FromType, ToType,
691 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000692 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000693 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000694 } else if (ToType->isBooleanType() &&
695 (FromType->isArithmeticType() ||
696 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +0000697 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +0000698 FromType->isBlockPointerType() ||
699 FromType->isMemberPointerType() ||
700 FromType->isNullPtrType())) {
701 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000702 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000703 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000704 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000705 Context.typesAreCompatible(ToType, FromType)) {
706 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000707 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000708 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
709 // Treat a conversion that strips "noreturn" as an identity conversion.
710 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000711 } else {
712 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000713 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000714 }
715
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000716 QualType CanonFrom;
717 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000718 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000719 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000720 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000721 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000722 CanonFrom = Context.getCanonicalType(FromType);
723 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000724 } else {
725 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000726 SCS.Third = ICK_Identity;
727
Mike Stump11289f42009-09-09 15:08:12 +0000728 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000729 // [...] Any difference in top-level cv-qualification is
730 // subsumed by the initialization itself and does not constitute
731 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000732 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000733 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000734 if (CanonFrom.getLocalUnqualifiedType()
735 == CanonTo.getLocalUnqualifiedType() &&
736 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000737 FromType = ToType;
738 CanonFrom = CanonTo;
739 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000740 }
741
742 // If we have not converted the argument type to the parameter type,
743 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000744 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000745 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000746
John McCall0d1da222010-01-12 00:44:57 +0000747 SCS.setToType(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000748 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000749}
750
751/// IsIntegralPromotion - Determines whether the conversion from the
752/// expression From (whose potentially-adjusted type is FromType) to
753/// ToType is an integral promotion (C++ 4.5). If so, returns true and
754/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000755bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000756 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000757 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000758 if (!To) {
759 return false;
760 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000761
762 // An rvalue of type char, signed char, unsigned char, short int, or
763 // unsigned short int can be converted to an rvalue of type int if
764 // int can represent all the values of the source type; otherwise,
765 // the source rvalue can be converted to an rvalue of type unsigned
766 // int (C++ 4.5p1).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000767 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000768 if (// We can promote any signed, promotable integer type to an int
769 (FromType->isSignedIntegerType() ||
770 // We can promote any unsigned integer type whose size is
771 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000772 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000773 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000774 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000775 }
776
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000777 return To->getKind() == BuiltinType::UInt;
778 }
779
780 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
781 // can be converted to an rvalue of the first of the following types
782 // that can represent all the values of its underlying type: int,
783 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +0000784
785 // We pre-calculate the promotion type for enum types.
786 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
787 if (ToType->isIntegerType())
788 return Context.hasSameUnqualifiedType(ToType,
789 FromEnumType->getDecl()->getPromotionType());
790
791 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000792 // Determine whether the type we're converting from is signed or
793 // unsigned.
794 bool FromIsSigned;
795 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +0000796
797 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
798 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000799
800 // The types we'll try to promote to, in the appropriate
801 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000802 QualType PromoteTypes[6] = {
803 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000804 Context.LongTy, Context.UnsignedLongTy ,
805 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000806 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000807 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000808 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
809 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000810 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000811 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
812 // We found the type that we can promote to. If this is the
813 // type we wanted, we have a promotion. Otherwise, no
814 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000815 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000816 }
817 }
818 }
819
820 // An rvalue for an integral bit-field (9.6) can be converted to an
821 // rvalue of type int if int can represent all the values of the
822 // bit-field; otherwise, it can be converted to unsigned int if
823 // unsigned int can represent all the values of the bit-field. If
824 // the bit-field is larger yet, no integral promotion applies to
825 // it. If the bit-field has an enumerated type, it is treated as any
826 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000827 // FIXME: We should delay checking of bit-fields until we actually perform the
828 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000829 using llvm::APSInt;
830 if (From)
831 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000832 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000833 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
834 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
835 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
836 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000837
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000838 // Are we promoting to an int from a bitfield that fits in an int?
839 if (BitWidth < ToSize ||
840 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
841 return To->getKind() == BuiltinType::Int;
842 }
Mike Stump11289f42009-09-09 15:08:12 +0000843
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000844 // Are we promoting to an unsigned int from an unsigned bitfield
845 // that fits into an unsigned int?
846 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
847 return To->getKind() == BuiltinType::UInt;
848 }
Mike Stump11289f42009-09-09 15:08:12 +0000849
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000850 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000851 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000852 }
Mike Stump11289f42009-09-09 15:08:12 +0000853
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000854 // An rvalue of type bool can be converted to an rvalue of type int,
855 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000856 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000857 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000858 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000859
860 return false;
861}
862
863/// IsFloatingPointPromotion - Determines whether the conversion from
864/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
865/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000866bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000867 /// An rvalue of type float can be converted to an rvalue of type
868 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000869 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
870 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000871 if (FromBuiltin->getKind() == BuiltinType::Float &&
872 ToBuiltin->getKind() == BuiltinType::Double)
873 return true;
874
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000875 // C99 6.3.1.5p1:
876 // When a float is promoted to double or long double, or a
877 // double is promoted to long double [...].
878 if (!getLangOptions().CPlusPlus &&
879 (FromBuiltin->getKind() == BuiltinType::Float ||
880 FromBuiltin->getKind() == BuiltinType::Double) &&
881 (ToBuiltin->getKind() == BuiltinType::LongDouble))
882 return true;
883 }
884
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000885 return false;
886}
887
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000888/// \brief Determine if a conversion is a complex promotion.
889///
890/// A complex promotion is defined as a complex -> complex conversion
891/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000892/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000893bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000894 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000895 if (!FromComplex)
896 return false;
897
John McCall9dd450b2009-09-21 23:43:11 +0000898 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000899 if (!ToComplex)
900 return false;
901
902 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000903 ToComplex->getElementType()) ||
904 IsIntegralPromotion(0, FromComplex->getElementType(),
905 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000906}
907
Douglas Gregor237f96c2008-11-26 23:31:11 +0000908/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
909/// the pointer type FromPtr to a pointer to type ToPointee, with the
910/// same type qualifiers as FromPtr has on its pointee type. ToType,
911/// if non-empty, will be a pointer to ToType that may or may not have
912/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000913static QualType
914BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000915 QualType ToPointee, QualType ToType,
916 ASTContext &Context) {
917 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
918 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000919 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000920
921 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000922 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000923 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000924 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000925 return ToType;
926
927 // Build a pointer to ToPointee. It has the right qualifiers
928 // already.
929 return Context.getPointerType(ToPointee);
930 }
931
932 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000933 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000934 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
935 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000936}
937
Fariborz Jahanian01cbe442009-12-16 23:13:33 +0000938/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
939/// the FromType, which is an objective-c pointer, to ToType, which may or may
940/// not have the right set of qualifiers.
941static QualType
942BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
943 QualType ToType,
944 ASTContext &Context) {
945 QualType CanonFromType = Context.getCanonicalType(FromType);
946 QualType CanonToType = Context.getCanonicalType(ToType);
947 Qualifiers Quals = CanonFromType.getQualifiers();
948
949 // Exact qualifier match -> return the pointer type we're converting to.
950 if (CanonToType.getLocalQualifiers() == Quals)
951 return ToType;
952
953 // Just build a canonical type that has the right qualifiers.
954 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
955}
956
Mike Stump11289f42009-09-09 15:08:12 +0000957static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000958 bool InOverloadResolution,
959 ASTContext &Context) {
960 // Handle value-dependent integral null pointer constants correctly.
961 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
962 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
963 Expr->getType()->isIntegralType())
964 return !InOverloadResolution;
965
Douglas Gregor56751b52009-09-25 04:25:58 +0000966 return Expr->isNullPointerConstant(Context,
967 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
968 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +0000969}
Mike Stump11289f42009-09-09 15:08:12 +0000970
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000971/// IsPointerConversion - Determines whether the conversion of the
972/// expression From, which has the (possibly adjusted) type FromType,
973/// can be converted to the type ToType via a pointer conversion (C++
974/// 4.10). If so, returns true and places the converted type (that
975/// might differ from ToType in its cv-qualifiers at some level) into
976/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000977///
Douglas Gregora29dc052008-11-27 01:19:21 +0000978/// This routine also supports conversions to and from block pointers
979/// and conversions with Objective-C's 'id', 'id<protocols...>', and
980/// pointers to interfaces. FIXME: Once we've determined the
981/// appropriate overloading rules for Objective-C, we may want to
982/// split the Objective-C checks into a different routine; however,
983/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000984/// conversions, so for now they live here. IncompatibleObjC will be
985/// set if the conversion is an allowed Objective-C conversion that
986/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000987bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000988 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000989 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +0000990 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +0000991 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +0000992 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
993 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000994
Mike Stump11289f42009-09-09 15:08:12 +0000995 // Conversion from a null pointer constant to any Objective-C pointer type.
996 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000997 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +0000998 ConvertedType = ToType;
999 return true;
1000 }
1001
Douglas Gregor231d1c62008-11-27 00:15:41 +00001002 // Blocks: Block pointers can be converted to void*.
1003 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001004 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001005 ConvertedType = ToType;
1006 return true;
1007 }
1008 // Blocks: A null pointer constant can be converted to a block
1009 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001010 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001011 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001012 ConvertedType = ToType;
1013 return true;
1014 }
1015
Sebastian Redl576fd422009-05-10 18:38:11 +00001016 // If the left-hand-side is nullptr_t, the right side can be a null
1017 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001018 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001019 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001020 ConvertedType = ToType;
1021 return true;
1022 }
1023
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001024 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001025 if (!ToTypePtr)
1026 return false;
1027
1028 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001029 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001030 ConvertedType = ToType;
1031 return true;
1032 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001033
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001034 // Beyond this point, both types need to be pointers
1035 // , including objective-c pointers.
1036 QualType ToPointeeType = ToTypePtr->getPointeeType();
1037 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1038 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1039 ToType, Context);
1040 return true;
1041
1042 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001043 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001044 if (!FromTypePtr)
1045 return false;
1046
1047 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001048
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001049 // An rvalue of type "pointer to cv T," where T is an object type,
1050 // can be converted to an rvalue of type "pointer to cv void" (C++
1051 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001052 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001053 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001054 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001055 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001056 return true;
1057 }
1058
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001059 // When we're overloading in C, we allow a special kind of pointer
1060 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001061 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001062 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001063 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001064 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001065 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001066 return true;
1067 }
1068
Douglas Gregor5c407d92008-10-23 00:40:37 +00001069 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001070 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001071 // An rvalue of type "pointer to cv D," where D is a class type,
1072 // can be converted to an rvalue of type "pointer to cv B," where
1073 // B is a base class (clause 10) of D. If B is an inaccessible
1074 // (clause 11) or ambiguous (10.2) base class of D, a program that
1075 // necessitates this conversion is ill-formed. The result of the
1076 // conversion is a pointer to the base class sub-object of the
1077 // derived class object. The null pointer value is converted to
1078 // the null pointer value of the destination type.
1079 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001080 // Note that we do not check for ambiguity or inaccessibility
1081 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001082 if (getLangOptions().CPlusPlus &&
1083 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001084 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001085 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001086 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001087 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001088 ToType, Context);
1089 return true;
1090 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001091
Douglas Gregora119f102008-12-19 19:13:09 +00001092 return false;
1093}
1094
1095/// isObjCPointerConversion - Determines whether this is an
1096/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1097/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001098bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001099 QualType& ConvertedType,
1100 bool &IncompatibleObjC) {
1101 if (!getLangOptions().ObjC1)
1102 return false;
1103
Steve Naroff7cae42b2009-07-10 23:34:53 +00001104 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001105 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001106 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001107 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001108
Steve Naroff7cae42b2009-07-10 23:34:53 +00001109 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001110 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001111 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001112 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001113 ConvertedType = ToType;
1114 return true;
1115 }
1116 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001117 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001118 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001119 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001120 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001121 ConvertedType = ToType;
1122 return true;
1123 }
1124 // Objective C++: We're able to convert from a pointer to an
1125 // interface to a pointer to a different interface.
1126 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1127 ConvertedType = ToType;
1128 return true;
1129 }
1130
1131 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1132 // Okay: this is some kind of implicit downcast of Objective-C
1133 // interfaces, which is permitted. However, we're going to
1134 // complain about it.
1135 IncompatibleObjC = true;
1136 ConvertedType = FromType;
1137 return true;
1138 }
Mike Stump11289f42009-09-09 15:08:12 +00001139 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001140 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001141 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001142 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001143 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001144 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001145 ToPointeeType = ToBlockPtr->getPointeeType();
1146 else
Douglas Gregora119f102008-12-19 19:13:09 +00001147 return false;
1148
Douglas Gregor033f56d2008-12-23 00:53:59 +00001149 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001150 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001151 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001152 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001153 FromPointeeType = FromBlockPtr->getPointeeType();
1154 else
Douglas Gregora119f102008-12-19 19:13:09 +00001155 return false;
1156
Douglas Gregora119f102008-12-19 19:13:09 +00001157 // If we have pointers to pointers, recursively check whether this
1158 // is an Objective-C conversion.
1159 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1160 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1161 IncompatibleObjC)) {
1162 // We always complain about this conversion.
1163 IncompatibleObjC = true;
1164 ConvertedType = ToType;
1165 return true;
1166 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001167 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001168 // differences in the argument and result types are in Objective-C
1169 // pointer conversions. If so, we permit the conversion (but
1170 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001171 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001172 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001173 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001174 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001175 if (FromFunctionType && ToFunctionType) {
1176 // If the function types are exactly the same, this isn't an
1177 // Objective-C pointer conversion.
1178 if (Context.getCanonicalType(FromPointeeType)
1179 == Context.getCanonicalType(ToPointeeType))
1180 return false;
1181
1182 // Perform the quick checks that will tell us whether these
1183 // function types are obviously different.
1184 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1185 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1186 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1187 return false;
1188
1189 bool HasObjCConversion = false;
1190 if (Context.getCanonicalType(FromFunctionType->getResultType())
1191 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1192 // Okay, the types match exactly. Nothing to do.
1193 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1194 ToFunctionType->getResultType(),
1195 ConvertedType, IncompatibleObjC)) {
1196 // Okay, we have an Objective-C pointer conversion.
1197 HasObjCConversion = true;
1198 } else {
1199 // Function types are too different. Abort.
1200 return false;
1201 }
Mike Stump11289f42009-09-09 15:08:12 +00001202
Douglas Gregora119f102008-12-19 19:13:09 +00001203 // Check argument types.
1204 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1205 ArgIdx != NumArgs; ++ArgIdx) {
1206 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1207 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1208 if (Context.getCanonicalType(FromArgType)
1209 == Context.getCanonicalType(ToArgType)) {
1210 // Okay, the types match exactly. Nothing to do.
1211 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1212 ConvertedType, IncompatibleObjC)) {
1213 // Okay, we have an Objective-C pointer conversion.
1214 HasObjCConversion = true;
1215 } else {
1216 // Argument types are too different. Abort.
1217 return false;
1218 }
1219 }
1220
1221 if (HasObjCConversion) {
1222 // We had an Objective-C conversion. Allow this pointer
1223 // conversion, but complain about it.
1224 ConvertedType = ToType;
1225 IncompatibleObjC = true;
1226 return true;
1227 }
1228 }
1229
Sebastian Redl72b597d2009-01-25 19:43:20 +00001230 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001231}
1232
Douglas Gregor39c16d42008-10-24 04:54:22 +00001233/// CheckPointerConversion - Check the pointer conversion from the
1234/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001235/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001236/// conversions for which IsPointerConversion has already returned
1237/// true. It returns true and produces a diagnostic if there was an
1238/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001239bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001240 CastExpr::CastKind &Kind,
1241 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001242 QualType FromType = From->getType();
1243
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001244 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1245 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001246 QualType FromPointeeType = FromPtrType->getPointeeType(),
1247 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001248
Douglas Gregor39c16d42008-10-24 04:54:22 +00001249 if (FromPointeeType->isRecordType() &&
1250 ToPointeeType->isRecordType()) {
1251 // We must have a derived-to-base conversion. Check an
1252 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001253 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1254 From->getExprLoc(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001255 From->getSourceRange(),
1256 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001257 return true;
1258
1259 // The conversion was successful.
1260 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001261 }
1262 }
Mike Stump11289f42009-09-09 15:08:12 +00001263 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001264 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001265 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001266 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001267 // Objective-C++ conversions are always okay.
1268 // FIXME: We should have a different class of conversions for the
1269 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001270 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001271 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001272
Steve Naroff7cae42b2009-07-10 23:34:53 +00001273 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001274 return false;
1275}
1276
Sebastian Redl72b597d2009-01-25 19:43:20 +00001277/// IsMemberPointerConversion - Determines whether the conversion of the
1278/// expression From, which has the (possibly adjusted) type FromType, can be
1279/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1280/// If so, returns true and places the converted type (that might differ from
1281/// ToType in its cv-qualifiers at some level) into ConvertedType.
1282bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001283 QualType ToType,
1284 bool InOverloadResolution,
1285 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001286 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001287 if (!ToTypePtr)
1288 return false;
1289
1290 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001291 if (From->isNullPointerConstant(Context,
1292 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1293 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001294 ConvertedType = ToType;
1295 return true;
1296 }
1297
1298 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001299 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001300 if (!FromTypePtr)
1301 return false;
1302
1303 // A pointer to member of B can be converted to a pointer to member of D,
1304 // where D is derived from B (C++ 4.11p2).
1305 QualType FromClass(FromTypePtr->getClass(), 0);
1306 QualType ToClass(ToTypePtr->getClass(), 0);
1307 // FIXME: What happens when these are dependent? Is this function even called?
1308
1309 if (IsDerivedFrom(ToClass, FromClass)) {
1310 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1311 ToClass.getTypePtr());
1312 return true;
1313 }
1314
1315 return false;
1316}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001317
Sebastian Redl72b597d2009-01-25 19:43:20 +00001318/// CheckMemberPointerConversion - Check the member pointer conversion from the
1319/// expression From to the type ToType. This routine checks for ambiguous or
1320/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1321/// for which IsMemberPointerConversion has already returned true. It returns
1322/// true and produces a diagnostic if there was an error, or returns false
1323/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001324bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001325 CastExpr::CastKind &Kind,
1326 bool IgnoreBaseAccess) {
1327 (void)IgnoreBaseAccess;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001328 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001329 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001330 if (!FromPtrType) {
1331 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001332 assert(From->isNullPointerConstant(Context,
1333 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001334 "Expr must be null pointer constant!");
1335 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001336 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001337 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001338
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001339 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001340 assert(ToPtrType && "No member pointer cast has a target type "
1341 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001342
Sebastian Redled8f2002009-01-28 18:33:18 +00001343 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1344 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001345
Sebastian Redled8f2002009-01-28 18:33:18 +00001346 // FIXME: What about dependent types?
1347 assert(FromClass->isRecordType() && "Pointer into non-class.");
1348 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001349
Douglas Gregor36d1b142009-10-06 17:59:45 +00001350 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1351 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001352 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1353 assert(DerivationOkay &&
1354 "Should not have been called if derivation isn't OK.");
1355 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001356
Sebastian Redled8f2002009-01-28 18:33:18 +00001357 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1358 getUnqualifiedType())) {
1359 // Derivation is ambiguous. Redo the check to find the exact paths.
1360 Paths.clear();
1361 Paths.setRecordingPaths(true);
1362 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1363 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1364 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001365
Sebastian Redled8f2002009-01-28 18:33:18 +00001366 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1367 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1368 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1369 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001370 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001371
Douglas Gregor89ee6822009-02-28 01:32:25 +00001372 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001373 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1374 << FromClass << ToClass << QualType(VBase, 0)
1375 << From->getSourceRange();
1376 return true;
1377 }
1378
Anders Carlssond7923c62009-08-22 23:33:40 +00001379 // Must be a base to derived member conversion.
1380 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001381 return false;
1382}
1383
Douglas Gregor9a657932008-10-21 23:43:52 +00001384/// IsQualificationConversion - Determines whether the conversion from
1385/// an rvalue of type FromType to ToType is a qualification conversion
1386/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001387bool
1388Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001389 FromType = Context.getCanonicalType(FromType);
1390 ToType = Context.getCanonicalType(ToType);
1391
1392 // If FromType and ToType are the same type, this is not a
1393 // qualification conversion.
1394 if (FromType == ToType)
1395 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001396
Douglas Gregor9a657932008-10-21 23:43:52 +00001397 // (C++ 4.4p4):
1398 // A conversion can add cv-qualifiers at levels other than the first
1399 // in multi-level pointers, subject to the following rules: [...]
1400 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001401 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001402 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001403 // Within each iteration of the loop, we check the qualifiers to
1404 // determine if this still looks like a qualification
1405 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001406 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001407 // until there are no more pointers or pointers-to-members left to
1408 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001409 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001410
1411 // -- for every j > 0, if const is in cv 1,j then const is in cv
1412 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001413 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001414 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001415
Douglas Gregor9a657932008-10-21 23:43:52 +00001416 // -- if the cv 1,j and cv 2,j are different, then const is in
1417 // every cv for 0 < k < j.
1418 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001419 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001420 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001421
Douglas Gregor9a657932008-10-21 23:43:52 +00001422 // Keep track of whether all prior cv-qualifiers in the "to" type
1423 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001424 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001425 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001426 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001427
1428 // We are left with FromType and ToType being the pointee types
1429 // after unwrapping the original FromType and ToType the same number
1430 // of types. If we unwrapped any pointers, and if FromType and
1431 // ToType have the same unqualified type (since we checked
1432 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001433 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001434}
1435
Douglas Gregor576e98c2009-01-30 23:27:23 +00001436/// Determines whether there is a user-defined conversion sequence
1437/// (C++ [over.ics.user]) that converts expression From to the type
1438/// ToType. If such a conversion exists, User will contain the
1439/// user-defined conversion sequence that performs such a conversion
1440/// and this routine will return true. Otherwise, this routine returns
1441/// false and User is unspecified.
1442///
1443/// \param AllowConversionFunctions true if the conversion should
1444/// consider conversion functions at all. If false, only constructors
1445/// will be considered.
1446///
1447/// \param AllowExplicit true if the conversion should consider C++0x
1448/// "explicit" conversion functions as well as non-explicit conversion
1449/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001450///
1451/// \param ForceRValue true if the expression should be treated as an rvalue
1452/// for overload resolution.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001453/// \param UserCast true if looking for user defined conversion for a static
1454/// cast.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001455OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1456 UserDefinedConversionSequence& User,
1457 OverloadCandidateSet& CandidateSet,
1458 bool AllowConversionFunctions,
1459 bool AllowExplicit,
1460 bool ForceRValue,
1461 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001462 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001463 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1464 // We're not going to find any constructors.
1465 } else if (CXXRecordDecl *ToRecordDecl
1466 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001467 // C++ [over.match.ctor]p1:
1468 // When objects of class type are direct-initialized (8.5), or
1469 // copy-initialized from an expression of the same or a
1470 // derived class type (8.5), overload resolution selects the
1471 // constructor. [...] For copy-initialization, the candidate
1472 // functions are all the converting constructors (12.3.1) of
1473 // that class. The argument list is the expression-list within
1474 // the parentheses of the initializer.
Douglas Gregor379d84b2009-11-13 18:44:21 +00001475 bool SuppressUserConversions = !UserCast;
1476 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1477 IsDerivedFrom(From->getType(), ToType)) {
1478 SuppressUserConversions = false;
1479 AllowConversionFunctions = false;
1480 }
1481
Mike Stump11289f42009-09-09 15:08:12 +00001482 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001483 = Context.DeclarationNames.getCXXConstructorName(
1484 Context.getCanonicalType(ToType).getUnqualifiedType());
1485 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001486 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001487 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001488 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001489 // Find the constructor (which may be a template).
1490 CXXConstructorDecl *Constructor = 0;
1491 FunctionTemplateDecl *ConstructorTmpl
1492 = dyn_cast<FunctionTemplateDecl>(*Con);
1493 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001494 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001495 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1496 else
1497 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001498
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001499 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001500 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001501 if (ConstructorTmpl)
John McCall6b51f282009-11-23 01:53:49 +00001502 AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
1503 &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001504 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001505 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001506 // Allow one user-defined conversion when user specifies a
1507 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001508 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001509 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001510 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001511 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001512 }
1513 }
1514
Douglas Gregor576e98c2009-01-30 23:27:23 +00001515 if (!AllowConversionFunctions) {
1516 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001517 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1518 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001519 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001520 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001521 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001522 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001523 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001524 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1525 // Add all of the conversion functions as candidates.
John McCalld14a8642009-11-21 08:51:07 +00001526 const UnresolvedSet *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001527 = FromRecordDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00001528 for (UnresolvedSet::iterator I = Conversions->begin(),
1529 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00001530 NamedDecl *D = *I;
1531 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1532 if (isa<UsingShadowDecl>(D))
1533 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1534
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001535 CXXConversionDecl *Conv;
1536 FunctionTemplateDecl *ConvTemplate;
John McCalld14a8642009-11-21 08:51:07 +00001537 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001538 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1539 else
John McCalld14a8642009-11-21 08:51:07 +00001540 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001541
1542 if (AllowExplicit || !Conv->isExplicit()) {
1543 if (ConvTemplate)
John McCall6e9f8f62009-12-03 04:06:58 +00001544 AddTemplateConversionCandidate(ConvTemplate, ActingContext,
1545 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001546 else
John McCall6e9f8f62009-12-03 04:06:58 +00001547 AddConversionCandidate(Conv, ActingContext, From, ToType,
1548 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001549 }
1550 }
1551 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001552 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001553
1554 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001555 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001556 case OR_Success:
1557 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001558 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001559 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1560 // C++ [over.ics.user]p1:
1561 // If the user-defined conversion is specified by a
1562 // constructor (12.3.1), the initial standard conversion
1563 // sequence converts the source type to the type required by
1564 // the argument of the constructor.
1565 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001566 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001567 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001568 User.EllipsisConversion = true;
1569 else {
1570 User.Before = Best->Conversions[0].Standard;
1571 User.EllipsisConversion = false;
1572 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001573 User.ConversionFunction = Constructor;
1574 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001575 User.After.setFromType(
1576 ThisType->getAs<PointerType>()->getPointeeType());
1577 User.After.setToType(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001578 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001579 } else if (CXXConversionDecl *Conversion
1580 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1581 // C++ [over.ics.user]p1:
1582 //
1583 // [...] If the user-defined conversion is specified by a
1584 // conversion function (12.3.2), the initial standard
1585 // conversion sequence converts the source type to the
1586 // implicit object parameter of the conversion function.
1587 User.Before = Best->Conversions[0].Standard;
1588 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001589 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001590
1591 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001592 // The second standard conversion sequence converts the
1593 // result of the user-defined conversion to the target type
1594 // for the sequence. Since an implicit conversion sequence
1595 // is an initialization, the special rules for
1596 // initialization by user-defined conversion apply when
1597 // selecting the best user-defined conversion for a
1598 // user-defined conversion sequence (see 13.3.3 and
1599 // 13.3.3.1).
1600 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001601 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001602 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001603 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001604 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001605 }
Mike Stump11289f42009-09-09 15:08:12 +00001606
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001607 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001608 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001609 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001610 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001611 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001612
1613 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001614 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001615 }
1616
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001617 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001618}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001619
1620bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001621Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001622 ImplicitConversionSequence ICS;
1623 OverloadCandidateSet CandidateSet;
1624 OverloadingResult OvResult =
1625 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1626 CandidateSet, true, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001627 if (OvResult == OR_Ambiguous)
1628 Diag(From->getSourceRange().getBegin(),
1629 diag::err_typecheck_ambiguous_condition)
1630 << From->getType() << ToType << From->getSourceRange();
1631 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1632 Diag(From->getSourceRange().getBegin(),
1633 diag::err_typecheck_nonviable_condition)
1634 << From->getType() << ToType << From->getSourceRange();
1635 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001636 return false;
John McCallad907772010-01-12 07:18:19 +00001637 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001638 return true;
1639}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001640
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001641/// CompareImplicitConversionSequences - Compare two implicit
1642/// conversion sequences to determine whether one is better than the
1643/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001644ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001645Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1646 const ImplicitConversionSequence& ICS2)
1647{
1648 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1649 // conversion sequences (as defined in 13.3.3.1)
1650 // -- a standard conversion sequence (13.3.3.1.1) is a better
1651 // conversion sequence than a user-defined conversion sequence or
1652 // an ellipsis conversion sequence, and
1653 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1654 // conversion sequence than an ellipsis conversion sequence
1655 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001656 //
John McCall0d1da222010-01-12 00:44:57 +00001657 // C++0x [over.best.ics]p10:
1658 // For the purpose of ranking implicit conversion sequences as
1659 // described in 13.3.3.2, the ambiguous conversion sequence is
1660 // treated as a user-defined sequence that is indistinguishable
1661 // from any other user-defined conversion sequence.
1662 if (ICS1.getKind() < ICS2.getKind()) {
1663 if (!(ICS1.isUserDefined() && ICS2.isAmbiguous()))
1664 return ImplicitConversionSequence::Better;
1665 } else if (ICS2.getKind() < ICS1.getKind()) {
1666 if (!(ICS2.isUserDefined() && ICS1.isAmbiguous()))
1667 return ImplicitConversionSequence::Worse;
1668 }
1669
1670 if (ICS1.isAmbiguous() || ICS2.isAmbiguous())
1671 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001672
1673 // Two implicit conversion sequences of the same form are
1674 // indistinguishable conversion sequences unless one of the
1675 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00001676 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001677 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00001678 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001679 // User-defined conversion sequence U1 is a better conversion
1680 // sequence than another user-defined conversion sequence U2 if
1681 // they contain the same user-defined conversion function or
1682 // constructor and if the second standard conversion sequence of
1683 // U1 is better than the second standard conversion sequence of
1684 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001685 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001686 ICS2.UserDefined.ConversionFunction)
1687 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1688 ICS2.UserDefined.After);
1689 }
1690
1691 return ImplicitConversionSequence::Indistinguishable;
1692}
1693
1694/// CompareStandardConversionSequences - Compare two standard
1695/// conversion sequences to determine whether one is better than the
1696/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001697ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001698Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1699 const StandardConversionSequence& SCS2)
1700{
1701 // Standard conversion sequence S1 is a better conversion sequence
1702 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1703
1704 // -- S1 is a proper subsequence of S2 (comparing the conversion
1705 // sequences in the canonical form defined by 13.3.3.1.1,
1706 // excluding any Lvalue Transformation; the identity conversion
1707 // sequence is considered to be a subsequence of any
1708 // non-identity conversion sequence) or, if not that,
1709 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1710 // Neither is a proper subsequence of the other. Do nothing.
1711 ;
1712 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1713 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001714 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001715 SCS1.Third == ICK_Identity))
1716 // SCS1 is a proper subsequence of SCS2.
1717 return ImplicitConversionSequence::Better;
1718 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1719 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001720 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001721 SCS2.Third == ICK_Identity))
1722 // SCS2 is a proper subsequence of SCS1.
1723 return ImplicitConversionSequence::Worse;
1724
1725 // -- the rank of S1 is better than the rank of S2 (by the rules
1726 // defined below), or, if not that,
1727 ImplicitConversionRank Rank1 = SCS1.getRank();
1728 ImplicitConversionRank Rank2 = SCS2.getRank();
1729 if (Rank1 < Rank2)
1730 return ImplicitConversionSequence::Better;
1731 else if (Rank2 < Rank1)
1732 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001733
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001734 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1735 // are indistinguishable unless one of the following rules
1736 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001737
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001738 // A conversion that is not a conversion of a pointer, or
1739 // pointer to member, to bool is better than another conversion
1740 // that is such a conversion.
1741 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1742 return SCS2.isPointerConversionToBool()
1743 ? ImplicitConversionSequence::Better
1744 : ImplicitConversionSequence::Worse;
1745
Douglas Gregor5c407d92008-10-23 00:40:37 +00001746 // C++ [over.ics.rank]p4b2:
1747 //
1748 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001749 // conversion of B* to A* is better than conversion of B* to
1750 // void*, and conversion of A* to void* is better than conversion
1751 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001752 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001753 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001754 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001755 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001756 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1757 // Exactly one of the conversion sequences is a conversion to
1758 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001759 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1760 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001761 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1762 // Neither conversion sequence converts to a void pointer; compare
1763 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001764 if (ImplicitConversionSequence::CompareKind DerivedCK
1765 = CompareDerivedToBaseConversions(SCS1, SCS2))
1766 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001767 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1768 // Both conversion sequences are conversions to void
1769 // pointers. Compare the source types to determine if there's an
1770 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00001771 QualType FromType1 = SCS1.getFromType();
1772 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001773
1774 // Adjust the types we're converting from via the array-to-pointer
1775 // conversion, if we need to.
1776 if (SCS1.First == ICK_Array_To_Pointer)
1777 FromType1 = Context.getArrayDecayedType(FromType1);
1778 if (SCS2.First == ICK_Array_To_Pointer)
1779 FromType2 = Context.getArrayDecayedType(FromType2);
1780
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001781 QualType FromPointee1
1782 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1783 QualType FromPointee2
1784 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001785
Douglas Gregor1aa450a2009-12-13 21:37:05 +00001786 if (IsDerivedFrom(FromPointee2, FromPointee1))
1787 return ImplicitConversionSequence::Better;
1788 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1789 return ImplicitConversionSequence::Worse;
1790
1791 // Objective-C++: If one interface is more specific than the
1792 // other, it is the better one.
1793 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1794 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1795 if (FromIface1 && FromIface1) {
1796 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1797 return ImplicitConversionSequence::Better;
1798 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1799 return ImplicitConversionSequence::Worse;
1800 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001801 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001802
1803 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1804 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001805 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001806 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001807 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001808
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001809 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001810 // C++0x [over.ics.rank]p3b4:
1811 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1812 // implicit object parameter of a non-static member function declared
1813 // without a ref-qualifier, and S1 binds an rvalue reference to an
1814 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001815 // FIXME: We don't know if we're dealing with the implicit object parameter,
1816 // or if the member function in this case has a ref qualifier.
1817 // (Of course, we don't have ref qualifiers yet.)
1818 if (SCS1.RRefBinding != SCS2.RRefBinding)
1819 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1820 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001821
1822 // C++ [over.ics.rank]p3b4:
1823 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1824 // which the references refer are the same type except for
1825 // top-level cv-qualifiers, and the type to which the reference
1826 // initialized by S2 refers is more cv-qualified than the type
1827 // to which the reference initialized by S1 refers.
John McCall0d1da222010-01-12 00:44:57 +00001828 QualType T1 = SCS1.getToType();
1829 QualType T2 = SCS2.getToType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001830 T1 = Context.getCanonicalType(T1);
1831 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001832 Qualifiers T1Quals, T2Quals;
1833 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1834 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1835 if (UnqualT1 == UnqualT2) {
1836 // If the type is an array type, promote the element qualifiers to the type
1837 // for comparison.
1838 if (isa<ArrayType>(T1) && T1Quals)
1839 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1840 if (isa<ArrayType>(T2) && T2Quals)
1841 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001842 if (T2.isMoreQualifiedThan(T1))
1843 return ImplicitConversionSequence::Better;
1844 else if (T1.isMoreQualifiedThan(T2))
1845 return ImplicitConversionSequence::Worse;
1846 }
1847 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001848
1849 return ImplicitConversionSequence::Indistinguishable;
1850}
1851
1852/// CompareQualificationConversions - Compares two standard conversion
1853/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001854/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1855ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001856Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001857 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001858 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001859 // -- S1 and S2 differ only in their qualification conversion and
1860 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1861 // cv-qualification signature of type T1 is a proper subset of
1862 // the cv-qualification signature of type T2, and S1 is not the
1863 // deprecated string literal array-to-pointer conversion (4.2).
1864 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1865 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1866 return ImplicitConversionSequence::Indistinguishable;
1867
1868 // FIXME: the example in the standard doesn't use a qualification
1869 // conversion (!)
1870 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1871 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1872 T1 = Context.getCanonicalType(T1);
1873 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00001874 Qualifiers T1Quals, T2Quals;
1875 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1876 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001877
1878 // If the types are the same, we won't learn anything by unwrapped
1879 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00001880 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001881 return ImplicitConversionSequence::Indistinguishable;
1882
Chandler Carruth607f38e2009-12-29 07:16:59 +00001883 // If the type is an array type, promote the element qualifiers to the type
1884 // for comparison.
1885 if (isa<ArrayType>(T1) && T1Quals)
1886 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1887 if (isa<ArrayType>(T2) && T2Quals)
1888 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1889
Mike Stump11289f42009-09-09 15:08:12 +00001890 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001891 = ImplicitConversionSequence::Indistinguishable;
1892 while (UnwrapSimilarPointerTypes(T1, T2)) {
1893 // Within each iteration of the loop, we check the qualifiers to
1894 // determine if this still looks like a qualification
1895 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001896 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001897 // until there are no more pointers or pointers-to-members left
1898 // to unwrap. This essentially mimics what
1899 // IsQualificationConversion does, but here we're checking for a
1900 // strict subset of qualifiers.
1901 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1902 // The qualifiers are the same, so this doesn't tell us anything
1903 // about how the sequences rank.
1904 ;
1905 else if (T2.isMoreQualifiedThan(T1)) {
1906 // T1 has fewer qualifiers, so it could be the better sequence.
1907 if (Result == ImplicitConversionSequence::Worse)
1908 // Neither has qualifiers that are a subset of the other's
1909 // qualifiers.
1910 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001911
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001912 Result = ImplicitConversionSequence::Better;
1913 } else if (T1.isMoreQualifiedThan(T2)) {
1914 // T2 has fewer qualifiers, so it could be the better sequence.
1915 if (Result == ImplicitConversionSequence::Better)
1916 // Neither has qualifiers that are a subset of the other's
1917 // qualifiers.
1918 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001919
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001920 Result = ImplicitConversionSequence::Worse;
1921 } else {
1922 // Qualifiers are disjoint.
1923 return ImplicitConversionSequence::Indistinguishable;
1924 }
1925
1926 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001927 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001928 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001929 }
1930
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001931 // Check that the winning standard conversion sequence isn't using
1932 // the deprecated string literal array to pointer conversion.
1933 switch (Result) {
1934 case ImplicitConversionSequence::Better:
1935 if (SCS1.Deprecated)
1936 Result = ImplicitConversionSequence::Indistinguishable;
1937 break;
1938
1939 case ImplicitConversionSequence::Indistinguishable:
1940 break;
1941
1942 case ImplicitConversionSequence::Worse:
1943 if (SCS2.Deprecated)
1944 Result = ImplicitConversionSequence::Indistinguishable;
1945 break;
1946 }
1947
1948 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001949}
1950
Douglas Gregor5c407d92008-10-23 00:40:37 +00001951/// CompareDerivedToBaseConversions - Compares two standard conversion
1952/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001953/// various kinds of derived-to-base conversions (C++
1954/// [over.ics.rank]p4b3). As part of these checks, we also look at
1955/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001956ImplicitConversionSequence::CompareKind
1957Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1958 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00001959 QualType FromType1 = SCS1.getFromType();
1960 QualType ToType1 = SCS1.getToType();
1961 QualType FromType2 = SCS2.getFromType();
1962 QualType ToType2 = SCS2.getToType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001963
1964 // Adjust the types we're converting from via the array-to-pointer
1965 // conversion, if we need to.
1966 if (SCS1.First == ICK_Array_To_Pointer)
1967 FromType1 = Context.getArrayDecayedType(FromType1);
1968 if (SCS2.First == ICK_Array_To_Pointer)
1969 FromType2 = Context.getArrayDecayedType(FromType2);
1970
1971 // Canonicalize all of the types.
1972 FromType1 = Context.getCanonicalType(FromType1);
1973 ToType1 = Context.getCanonicalType(ToType1);
1974 FromType2 = Context.getCanonicalType(FromType2);
1975 ToType2 = Context.getCanonicalType(ToType2);
1976
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001977 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001978 //
1979 // If class B is derived directly or indirectly from class A and
1980 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001981 //
1982 // For Objective-C, we let A, B, and C also be Objective-C
1983 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001984
1985 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00001986 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00001987 SCS2.Second == ICK_Pointer_Conversion &&
1988 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1989 FromType1->isPointerType() && FromType2->isPointerType() &&
1990 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001991 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001992 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001993 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001994 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001995 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001996 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001997 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001998 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001999
John McCall9dd450b2009-09-21 23:43:11 +00002000 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2001 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2002 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2003 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002004
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002005 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002006 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2007 if (IsDerivedFrom(ToPointee1, ToPointee2))
2008 return ImplicitConversionSequence::Better;
2009 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2010 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002011
2012 if (ToIface1 && ToIface2) {
2013 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2014 return ImplicitConversionSequence::Better;
2015 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2016 return ImplicitConversionSequence::Worse;
2017 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002018 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002019
2020 // -- conversion of B* to A* is better than conversion of C* to A*,
2021 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2022 if (IsDerivedFrom(FromPointee2, FromPointee1))
2023 return ImplicitConversionSequence::Better;
2024 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2025 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002026
Douglas Gregor237f96c2008-11-26 23:31:11 +00002027 if (FromIface1 && FromIface2) {
2028 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2029 return ImplicitConversionSequence::Better;
2030 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2031 return ImplicitConversionSequence::Worse;
2032 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002033 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002034 }
2035
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002036 // Compare based on reference bindings.
2037 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
2038 SCS1.Second == ICK_Derived_To_Base) {
2039 // -- binding of an expression of type C to a reference of type
2040 // B& is better than binding an expression of type C to a
2041 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002042 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2043 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002044 if (IsDerivedFrom(ToType1, ToType2))
2045 return ImplicitConversionSequence::Better;
2046 else if (IsDerivedFrom(ToType2, ToType1))
2047 return ImplicitConversionSequence::Worse;
2048 }
2049
Douglas Gregor2fe98832008-11-03 19:09:14 +00002050 // -- binding of an expression of type B to a reference of type
2051 // A& is better than binding an expression of type C to a
2052 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002053 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2054 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002055 if (IsDerivedFrom(FromType2, FromType1))
2056 return ImplicitConversionSequence::Better;
2057 else if (IsDerivedFrom(FromType1, FromType2))
2058 return ImplicitConversionSequence::Worse;
2059 }
2060 }
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002061
2062 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002063 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2064 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2065 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2066 const MemberPointerType * FromMemPointer1 =
2067 FromType1->getAs<MemberPointerType>();
2068 const MemberPointerType * ToMemPointer1 =
2069 ToType1->getAs<MemberPointerType>();
2070 const MemberPointerType * FromMemPointer2 =
2071 FromType2->getAs<MemberPointerType>();
2072 const MemberPointerType * ToMemPointer2 =
2073 ToType2->getAs<MemberPointerType>();
2074 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2075 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2076 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2077 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2078 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2079 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2080 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2081 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002082 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002083 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2084 if (IsDerivedFrom(ToPointee1, ToPointee2))
2085 return ImplicitConversionSequence::Worse;
2086 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2087 return ImplicitConversionSequence::Better;
2088 }
2089 // conversion of B::* to C::* is better than conversion of A::* to C::*
2090 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2091 if (IsDerivedFrom(FromPointee1, FromPointee2))
2092 return ImplicitConversionSequence::Better;
2093 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2094 return ImplicitConversionSequence::Worse;
2095 }
2096 }
2097
Douglas Gregor2fe98832008-11-03 19:09:14 +00002098 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
2099 SCS1.Second == ICK_Derived_To_Base) {
2100 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002101 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2102 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002103 if (IsDerivedFrom(ToType1, ToType2))
2104 return ImplicitConversionSequence::Better;
2105 else if (IsDerivedFrom(ToType2, ToType1))
2106 return ImplicitConversionSequence::Worse;
2107 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002108
Douglas Gregor2fe98832008-11-03 19:09:14 +00002109 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002110 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2111 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002112 if (IsDerivedFrom(FromType2, FromType1))
2113 return ImplicitConversionSequence::Better;
2114 else if (IsDerivedFrom(FromType1, FromType2))
2115 return ImplicitConversionSequence::Worse;
2116 }
2117 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002118
Douglas Gregor5c407d92008-10-23 00:40:37 +00002119 return ImplicitConversionSequence::Indistinguishable;
2120}
2121
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002122/// TryCopyInitialization - Try to copy-initialize a value of type
2123/// ToType from the expression From. Return the implicit conversion
2124/// sequence required to pass this argument, which may be a bad
2125/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002126/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00002127/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2128/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00002129ImplicitConversionSequence
2130Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002131 bool SuppressUserConversions, bool ForceRValue,
2132 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002133 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002134 ImplicitConversionSequence ICS;
John McCall6a61b522010-01-13 09:16:55 +00002135 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Mike Stump11289f42009-09-09 15:08:12 +00002136 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002137 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002138 SuppressUserConversions,
2139 /*AllowExplicit=*/false,
2140 ForceRValue,
2141 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002142 return ICS;
2143 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002144 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002145 SuppressUserConversions,
2146 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002147 ForceRValue,
2148 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002149 }
2150}
2151
Sebastian Redl42e92c42009-04-12 17:16:29 +00002152/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2153/// the expression @p From. Returns true (and emits a diagnostic) if there was
2154/// an error, returns false if the initialization succeeded. Elidable should
2155/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2156/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002157bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002158 AssignmentAction Action, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002159 if (!getLangOptions().CPlusPlus) {
2160 // In C, argument passing is the same as performing an assignment.
2161 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002162
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002163 AssignConvertType ConvTy =
2164 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002165 if (ConvTy != Compatible &&
2166 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2167 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002168
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002169 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002170 FromType, From, Action);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002171 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002172
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002173 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002174 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002175 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002176 /*SuppressUserConversions=*/false,
2177 /*AllowExplicit=*/false,
2178 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002179
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002180 if (!PerformImplicitConversion(From, ToType, Action,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002181 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002182 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00002183 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002184 return Diag(From->getSourceRange().getBegin(),
2185 diag::err_typecheck_convert_incompatible)
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002186 << ToType << From->getType() << Action << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002187 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002188}
2189
Douglas Gregor436424c2008-11-18 23:14:02 +00002190/// TryObjectArgumentInitialization - Try to initialize the object
2191/// parameter of the given member function (@c Method) from the
2192/// expression @p From.
2193ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002194Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002195 CXXMethodDecl *Method,
2196 CXXRecordDecl *ActingContext) {
2197 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002198 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2199 // const volatile object.
2200 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2201 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2202 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002203
2204 // Set up the conversion sequence as a "bad" conversion, to allow us
2205 // to exit early.
2206 ImplicitConversionSequence ICS;
2207 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00002208 ICS.setBad();
Douglas Gregor436424c2008-11-18 23:14:02 +00002209
2210 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002211 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002212 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002213 FromType = PT->getPointeeType();
2214
2215 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002216
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002217 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002218 // where X is the class of which the function is a member
2219 // (C++ [over.match.funcs]p4). However, when finding an implicit
2220 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002221 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002222 // (C++ [over.match.funcs]p5). We perform a simplified version of
2223 // reference binding here, that allows class rvalues to bind to
2224 // non-constant references.
2225
2226 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2227 // with the implicit object parameter (C++ [over.match.funcs]p5).
2228 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002229 if (ImplicitParamType.getCVRQualifiers()
2230 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002231 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall47000992010-01-14 03:28:57 +00002232 ICS.Bad.init(BadConversionSequence::bad_qualifiers,
2233 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002234 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002235 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002236
2237 // Check that we have either the same type or a derived type. It
2238 // affects the conversion rank.
2239 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002240 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor436424c2008-11-18 23:14:02 +00002241 ICS.Standard.Second = ICK_Identity;
2242 else if (IsDerivedFrom(FromType, ClassType))
2243 ICS.Standard.Second = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002244 else {
2245 ICS.Bad.init(BadConversionSequence::unrelated_class, FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002246 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002247 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002248
2249 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002250 ICS.setStandard();
2251 ICS.Standard.setFromType(FromType);
2252 ICS.Standard.setToType(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002253 ICS.Standard.ReferenceBinding = true;
2254 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002255 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002256 return ICS;
2257}
2258
2259/// PerformObjectArgumentInitialization - Perform initialization of
2260/// the implicit object parameter for the given Method with the given
2261/// expression.
2262bool
2263Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002264 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002265 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002266 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002267
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002268 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002269 FromRecordType = PT->getPointeeType();
2270 DestType = Method->getThisType(Context);
2271 } else {
2272 FromRecordType = From->getType();
2273 DestType = ImplicitParamRecordType;
2274 }
2275
John McCall6e9f8f62009-12-03 04:06:58 +00002276 // Note that we always use the true parent context when performing
2277 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002278 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002279 = TryObjectArgumentInitialization(From->getType(), Method,
2280 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002281 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002282 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002283 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002284 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002285
Douglas Gregor436424c2008-11-18 23:14:02 +00002286 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002287 CheckDerivedToBaseConversion(FromRecordType,
2288 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002289 From->getSourceRange().getBegin(),
2290 From->getSourceRange()))
2291 return true;
2292
Mike Stump11289f42009-09-09 15:08:12 +00002293 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002294 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002295 return false;
2296}
2297
Douglas Gregor5fb53972009-01-14 15:45:31 +00002298/// TryContextuallyConvertToBool - Attempt to contextually convert the
2299/// expression From to bool (C++0x [conv]p3).
2300ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002301 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002302 // FIXME: Are these flags correct?
2303 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002304 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002305 /*ForceRValue=*/false,
2306 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002307}
2308
2309/// PerformContextuallyConvertToBool - Perform a contextual conversion
2310/// of the expression From to bool (C++0x [conv]p3).
2311bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2312 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00002313 if (!ICS.isBad())
2314 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002315
Fariborz Jahanian76197412009-11-18 18:26:29 +00002316 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002317 return Diag(From->getSourceRange().getBegin(),
2318 diag::err_typecheck_bool_condition)
2319 << From->getType() << From->getSourceRange();
2320 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002321}
2322
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002323/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002324/// candidate functions, using the given function call arguments. If
2325/// @p SuppressUserConversions, then don't allow user-defined
2326/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002327/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2328/// hacky way to implement the overloading rules for elidable copy
2329/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002330///
2331/// \para PartialOverloading true if we are performing "partial" overloading
2332/// based on an incomplete set of function arguments. This feature is used by
2333/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002334void
2335Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002336 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002337 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002338 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002339 bool ForceRValue,
2340 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002341 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002342 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002343 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002344 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002345 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002346
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002347 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002348 if (!isa<CXXConstructorDecl>(Method)) {
2349 // If we get here, it's because we're calling a member function
2350 // that is named without a member access expression (e.g.,
2351 // "this->f") that was either written explicitly or created
2352 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002353 // function, e.g., X::f(). We use an empty type for the implied
2354 // object argument (C++ [over.call.func]p3), and the acting context
2355 // is irrelevant.
2356 AddMethodCandidate(Method, Method->getParent(),
2357 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002358 SuppressUserConversions, ForceRValue);
2359 return;
2360 }
2361 // We treat a constructor like a non-member function, since its object
2362 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002363 }
2364
Douglas Gregorff7028a2009-11-13 23:59:09 +00002365 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002366 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002367
Douglas Gregor27381f32009-11-23 12:27:39 +00002368 // Overload resolution is always an unevaluated context.
2369 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2370
Douglas Gregorffe14e32009-11-14 01:20:54 +00002371 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2372 // C++ [class.copy]p3:
2373 // A member function template is never instantiated to perform the copy
2374 // of a class object to an object of its class type.
2375 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2376 if (NumArgs == 1 &&
2377 Constructor->isCopyConstructorLikeSpecialization() &&
2378 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2379 return;
2380 }
2381
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002382 // Add this candidate
2383 CandidateSet.push_back(OverloadCandidate());
2384 OverloadCandidate& Candidate = CandidateSet.back();
2385 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002386 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002387 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002388 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002389
2390 unsigned NumArgsInProto = Proto->getNumArgs();
2391
2392 // (C++ 13.3.2p2): A candidate function having fewer than m
2393 // parameters is viable only if it has an ellipsis in its parameter
2394 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002395 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2396 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002397 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002398 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002399 return;
2400 }
2401
2402 // (C++ 13.3.2p2): A candidate function having more than m parameters
2403 // is viable only if the (m+1)st parameter has a default argument
2404 // (8.3.6). For the purposes of overload resolution, the
2405 // parameter list is truncated on the right, so that there are
2406 // exactly m parameters.
2407 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002408 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002409 // Not enough arguments.
2410 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002411 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002412 return;
2413 }
2414
2415 // Determine the implicit conversion sequences for each of the
2416 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002417 Candidate.Conversions.resize(NumArgs);
2418 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2419 if (ArgIdx < NumArgsInProto) {
2420 // (C++ 13.3.2p3): for F to be a viable function, there shall
2421 // exist for each argument an implicit conversion sequence
2422 // (13.3.3.1) that converts that argument to the corresponding
2423 // parameter of F.
2424 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002425 Candidate.Conversions[ArgIdx]
2426 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002427 SuppressUserConversions, ForceRValue,
2428 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002429 if (Candidate.Conversions[ArgIdx].isBad()) {
2430 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002431 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00002432 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00002433 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002434 } else {
2435 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2436 // argument for which there is no corresponding parameter is
2437 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002438 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002439 }
2440 }
2441}
2442
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002443/// \brief Add all of the function declarations in the given function set to
2444/// the overload canddiate set.
2445void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2446 Expr **Args, unsigned NumArgs,
2447 OverloadCandidateSet& CandidateSet,
2448 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002449 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002450 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002451 F != FEnd; ++F) {
John McCall6e9f8f62009-12-03 04:06:58 +00002452 // FIXME: using declarations
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002453 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2454 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2455 AddMethodCandidate(cast<CXXMethodDecl>(FD),
John McCall6e9f8f62009-12-03 04:06:58 +00002456 cast<CXXMethodDecl>(FD)->getParent(),
2457 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002458 CandidateSet, SuppressUserConversions);
2459 else
2460 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2461 SuppressUserConversions);
2462 } else {
2463 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2464 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2465 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2466 AddMethodTemplateCandidate(FunTmpl,
John McCall6e9f8f62009-12-03 04:06:58 +00002467 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002468 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002469 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002470 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002471 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002472 else
2473 AddTemplateOverloadCandidate(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00002474 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002475 Args, NumArgs, CandidateSet,
2476 SuppressUserConversions);
2477 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002478 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002479}
2480
John McCallf0f1cf02009-11-17 07:50:12 +00002481/// AddMethodCandidate - Adds a named decl (which is some kind of
2482/// method) as a method candidate to the given overload set.
John McCall6e9f8f62009-12-03 04:06:58 +00002483void Sema::AddMethodCandidate(NamedDecl *Decl,
2484 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002485 Expr **Args, unsigned NumArgs,
2486 OverloadCandidateSet& CandidateSet,
2487 bool SuppressUserConversions, bool ForceRValue) {
John McCall6e9f8f62009-12-03 04:06:58 +00002488 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002489
2490 if (isa<UsingShadowDecl>(Decl))
2491 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2492
2493 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2494 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2495 "Expected a member function template");
John McCall6e9f8f62009-12-03 04:06:58 +00002496 AddMethodTemplateCandidate(TD, ActingContext, /*ExplicitArgs*/ 0,
2497 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002498 CandidateSet,
2499 SuppressUserConversions,
2500 ForceRValue);
2501 } else {
John McCall6e9f8f62009-12-03 04:06:58 +00002502 AddMethodCandidate(cast<CXXMethodDecl>(Decl), ActingContext,
2503 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002504 CandidateSet, SuppressUserConversions, ForceRValue);
2505 }
2506}
2507
Douglas Gregor436424c2008-11-18 23:14:02 +00002508/// AddMethodCandidate - Adds the given C++ member function to the set
2509/// of candidate functions, using the given function call arguments
2510/// and the object argument (@c Object). For example, in a call
2511/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2512/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2513/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002514/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2515/// a slightly hacky way to implement the overloading rules for elidable copy
2516/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002517void
John McCall6e9f8f62009-12-03 04:06:58 +00002518Sema::AddMethodCandidate(CXXMethodDecl *Method, CXXRecordDecl *ActingContext,
2519 QualType ObjectType, Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002520 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002521 bool SuppressUserConversions, bool ForceRValue) {
2522 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002523 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002524 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002525 assert(!isa<CXXConstructorDecl>(Method) &&
2526 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002527
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002528 if (!CandidateSet.isNewCandidate(Method))
2529 return;
2530
Douglas Gregor27381f32009-11-23 12:27:39 +00002531 // Overload resolution is always an unevaluated context.
2532 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2533
Douglas Gregor436424c2008-11-18 23:14:02 +00002534 // Add this candidate
2535 CandidateSet.push_back(OverloadCandidate());
2536 OverloadCandidate& Candidate = CandidateSet.back();
2537 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002538 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002539 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002540
2541 unsigned NumArgsInProto = Proto->getNumArgs();
2542
2543 // (C++ 13.3.2p2): A candidate function having fewer than m
2544 // parameters is viable only if it has an ellipsis in its parameter
2545 // list (8.3.5).
2546 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2547 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002548 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002549 return;
2550 }
2551
2552 // (C++ 13.3.2p2): A candidate function having more than m parameters
2553 // is viable only if the (m+1)st parameter has a default argument
2554 // (8.3.6). For the purposes of overload resolution, the
2555 // parameter list is truncated on the right, so that there are
2556 // exactly m parameters.
2557 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2558 if (NumArgs < MinRequiredArgs) {
2559 // Not enough arguments.
2560 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002561 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002562 return;
2563 }
2564
2565 Candidate.Viable = true;
2566 Candidate.Conversions.resize(NumArgs + 1);
2567
John McCall6e9f8f62009-12-03 04:06:58 +00002568 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002569 // The implicit object argument is ignored.
2570 Candidate.IgnoreObjectArgument = true;
2571 else {
2572 // Determine the implicit conversion sequence for the object
2573 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002574 Candidate.Conversions[0]
2575 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002576 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002577 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002578 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002579 return;
2580 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002581 }
2582
2583 // Determine the implicit conversion sequences for each of the
2584 // arguments.
2585 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2586 if (ArgIdx < NumArgsInProto) {
2587 // (C++ 13.3.2p3): for F to be a viable function, there shall
2588 // exist for each argument an implicit conversion sequence
2589 // (13.3.3.1) that converts that argument to the corresponding
2590 // parameter of F.
2591 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002592 Candidate.Conversions[ArgIdx + 1]
2593 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002594 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002595 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002596 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002597 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002598 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00002599 break;
2600 }
2601 } else {
2602 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2603 // argument for which there is no corresponding parameter is
2604 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002605 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00002606 }
2607 }
2608}
2609
Douglas Gregor97628d62009-08-21 00:16:32 +00002610/// \brief Add a C++ member function template as a candidate to the candidate
2611/// set, using template argument deduction to produce an appropriate member
2612/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002613void
Douglas Gregor97628d62009-08-21 00:16:32 +00002614Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall6e9f8f62009-12-03 04:06:58 +00002615 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00002616 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00002617 QualType ObjectType,
2618 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002619 OverloadCandidateSet& CandidateSet,
2620 bool SuppressUserConversions,
2621 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002622 if (!CandidateSet.isNewCandidate(MethodTmpl))
2623 return;
2624
Douglas Gregor97628d62009-08-21 00:16:32 +00002625 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002626 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002627 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002628 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002629 // candidate functions in the usual way.113) A given name can refer to one
2630 // or more function templates and also to a set of overloaded non-template
2631 // functions. In such a case, the candidate functions generated from each
2632 // function template are combined with the set of non-template candidate
2633 // functions.
2634 TemplateDeductionInfo Info(Context);
2635 FunctionDecl *Specialization = 0;
2636 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002637 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002638 Args, NumArgs, Specialization, Info)) {
2639 // FIXME: Record what happened with template argument deduction, so
2640 // that we can give the user a beautiful diagnostic.
2641 (void)Result;
2642 return;
2643 }
Mike Stump11289f42009-09-09 15:08:12 +00002644
Douglas Gregor97628d62009-08-21 00:16:32 +00002645 // Add the function template specialization produced by template argument
2646 // deduction as a candidate.
2647 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002648 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002649 "Specialization is not a member function?");
John McCall6e9f8f62009-12-03 04:06:58 +00002650 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), ActingContext,
2651 ObjectType, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002652 CandidateSet, SuppressUserConversions, ForceRValue);
2653}
2654
Douglas Gregor05155d82009-08-21 23:19:43 +00002655/// \brief Add a C++ function template specialization as a candidate
2656/// in the candidate set, using template argument deduction to produce
2657/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002658void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002659Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00002660 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002661 Expr **Args, unsigned NumArgs,
2662 OverloadCandidateSet& CandidateSet,
2663 bool SuppressUserConversions,
2664 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002665 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2666 return;
2667
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002668 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002669 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002670 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002671 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002672 // candidate functions in the usual way.113) A given name can refer to one
2673 // or more function templates and also to a set of overloaded non-template
2674 // functions. In such a case, the candidate functions generated from each
2675 // function template are combined with the set of non-template candidate
2676 // functions.
2677 TemplateDeductionInfo Info(Context);
2678 FunctionDecl *Specialization = 0;
2679 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002680 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002681 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002682 // FIXME: Record what happened with template argument deduction, so
2683 // that we can give the user a beautiful diagnostic.
John McCalld681c392009-12-16 08:11:27 +00002684 (void) Result;
2685
2686 CandidateSet.push_back(OverloadCandidate());
2687 OverloadCandidate &Candidate = CandidateSet.back();
2688 Candidate.Function = FunctionTemplate->getTemplatedDecl();
2689 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002690 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00002691 Candidate.IsSurrogate = false;
2692 Candidate.IgnoreObjectArgument = false;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002693 return;
2694 }
Mike Stump11289f42009-09-09 15:08:12 +00002695
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002696 // Add the function template specialization produced by template argument
2697 // deduction as a candidate.
2698 assert(Specialization && "Missing function template specialization?");
2699 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2700 SuppressUserConversions, ForceRValue);
2701}
Mike Stump11289f42009-09-09 15:08:12 +00002702
Douglas Gregora1f013e2008-11-07 22:36:19 +00002703/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002704/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002705/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002706/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002707/// (which may or may not be the same type as the type that the
2708/// conversion function produces).
2709void
2710Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall6e9f8f62009-12-03 04:06:58 +00002711 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002712 Expr *From, QualType ToType,
2713 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002714 assert(!Conversion->getDescribedFunctionTemplate() &&
2715 "Conversion function templates use AddTemplateConversionCandidate");
2716
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002717 if (!CandidateSet.isNewCandidate(Conversion))
2718 return;
2719
Douglas Gregor27381f32009-11-23 12:27:39 +00002720 // Overload resolution is always an unevaluated context.
2721 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2722
Douglas Gregora1f013e2008-11-07 22:36:19 +00002723 // Add this candidate
2724 CandidateSet.push_back(OverloadCandidate());
2725 OverloadCandidate& Candidate = CandidateSet.back();
2726 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002727 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002728 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002729 Candidate.FinalConversion.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00002730 Candidate.FinalConversion.setFromType(Conversion->getConversionType());
2731 Candidate.FinalConversion.setToType(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00002732
Douglas Gregor436424c2008-11-18 23:14:02 +00002733 // Determine the implicit conversion sequence for the implicit
2734 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002735 Candidate.Viable = true;
2736 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00002737 Candidate.Conversions[0]
2738 = TryObjectArgumentInitialization(From->getType(), Conversion,
2739 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002740 // Conversion functions to a different type in the base class is visible in
2741 // the derived class. So, a derived to base conversion should not participate
2742 // in overload resolution.
2743 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2744 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00002745 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002746 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002747 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002748 return;
2749 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002750
2751 // We won't go through a user-define type conversion function to convert a
2752 // derived to base as such conversions are given Conversion Rank. They only
2753 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2754 QualType FromCanon
2755 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2756 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2757 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2758 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002759 Candidate.FailureKind = ovl_fail_bad_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002760 return;
2761 }
2762
Douglas Gregora1f013e2008-11-07 22:36:19 +00002763
2764 // To determine what the conversion from the result of calling the
2765 // conversion function to the type we're eventually trying to
2766 // convert to (ToType), we need to synthesize a call to the
2767 // conversion function and attempt copy initialization from it. This
2768 // makes sure that we get the right semantics with respect to
2769 // lvalues/rvalues and the type. Fortunately, we can allocate this
2770 // call on the stack and we don't need its arguments to be
2771 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002772 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002773 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00002774 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002775 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002776 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002777
2778 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002779 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2780 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002781 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002782 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002783 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002784 ImplicitConversionSequence ICS =
2785 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002786 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002787 /*ForceRValue=*/false,
2788 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002789
John McCall0d1da222010-01-12 00:44:57 +00002790 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002791 case ImplicitConversionSequence::StandardConversion:
2792 Candidate.FinalConversion = ICS.Standard;
2793 break;
2794
2795 case ImplicitConversionSequence::BadConversion:
2796 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002797 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002798 break;
2799
2800 default:
Mike Stump11289f42009-09-09 15:08:12 +00002801 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002802 "Can only end up with a standard conversion sequence or failure");
2803 }
2804}
2805
Douglas Gregor05155d82009-08-21 23:19:43 +00002806/// \brief Adds a conversion function template specialization
2807/// candidate to the overload set, using template argument deduction
2808/// to deduce the template arguments of the conversion function
2809/// template from the type that we are converting to (C++
2810/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002811void
Douglas Gregor05155d82009-08-21 23:19:43 +00002812Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6e9f8f62009-12-03 04:06:58 +00002813 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00002814 Expr *From, QualType ToType,
2815 OverloadCandidateSet &CandidateSet) {
2816 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2817 "Only conversion function templates permitted here");
2818
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002819 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2820 return;
2821
Douglas Gregor05155d82009-08-21 23:19:43 +00002822 TemplateDeductionInfo Info(Context);
2823 CXXConversionDecl *Specialization = 0;
2824 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002825 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002826 Specialization, Info)) {
2827 // FIXME: Record what happened with template argument deduction, so
2828 // that we can give the user a beautiful diagnostic.
2829 (void)Result;
2830 return;
2831 }
Mike Stump11289f42009-09-09 15:08:12 +00002832
Douglas Gregor05155d82009-08-21 23:19:43 +00002833 // Add the conversion function template specialization produced by
2834 // template argument deduction as a candidate.
2835 assert(Specialization && "Missing function template specialization?");
John McCall6e9f8f62009-12-03 04:06:58 +00002836 AddConversionCandidate(Specialization, ActingDC, From, ToType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00002837}
2838
Douglas Gregorab7897a2008-11-19 22:57:39 +00002839/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2840/// converts the given @c Object to a function pointer via the
2841/// conversion function @c Conversion, and then attempts to call it
2842/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2843/// the type of function that we'll eventually be calling.
2844void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall6e9f8f62009-12-03 04:06:58 +00002845 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002846 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00002847 QualType ObjectType,
2848 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002849 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002850 if (!CandidateSet.isNewCandidate(Conversion))
2851 return;
2852
Douglas Gregor27381f32009-11-23 12:27:39 +00002853 // Overload resolution is always an unevaluated context.
2854 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2855
Douglas Gregorab7897a2008-11-19 22:57:39 +00002856 CandidateSet.push_back(OverloadCandidate());
2857 OverloadCandidate& Candidate = CandidateSet.back();
2858 Candidate.Function = 0;
2859 Candidate.Surrogate = Conversion;
2860 Candidate.Viable = true;
2861 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002862 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002863 Candidate.Conversions.resize(NumArgs + 1);
2864
2865 // Determine the implicit conversion sequence for the implicit
2866 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002867 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00002868 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002869 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00002870 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002871 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002872 return;
2873 }
2874
2875 // The first conversion is actually a user-defined conversion whose
2876 // first conversion is ObjectInit's standard conversion (which is
2877 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00002878 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00002879 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002880 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002881 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002882 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002883 = Candidate.Conversions[0].UserDefined.Before;
2884 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2885
Mike Stump11289f42009-09-09 15:08:12 +00002886 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002887 unsigned NumArgsInProto = Proto->getNumArgs();
2888
2889 // (C++ 13.3.2p2): A candidate function having fewer than m
2890 // parameters is viable only if it has an ellipsis in its parameter
2891 // list (8.3.5).
2892 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2893 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002894 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002895 return;
2896 }
2897
2898 // Function types don't have any default arguments, so just check if
2899 // we have enough arguments.
2900 if (NumArgs < NumArgsInProto) {
2901 // Not enough arguments.
2902 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002903 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002904 return;
2905 }
2906
2907 // Determine the implicit conversion sequences for each of the
2908 // arguments.
2909 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2910 if (ArgIdx < NumArgsInProto) {
2911 // (C++ 13.3.2p3): for F to be a viable function, there shall
2912 // exist for each argument an implicit conversion sequence
2913 // (13.3.3.1) that converts that argument to the corresponding
2914 // parameter of F.
2915 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002916 Candidate.Conversions[ArgIdx + 1]
2917 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002918 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002919 /*ForceRValue=*/false,
2920 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00002921 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00002922 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002923 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002924 break;
2925 }
2926 } else {
2927 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2928 // argument for which there is no corresponding parameter is
2929 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002930 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00002931 }
2932 }
2933}
2934
Mike Stump87c57ac2009-05-16 07:39:55 +00002935// FIXME: This will eventually be removed, once we've migrated all of the
2936// operator overloading logic over to the scheme used by binary operators, which
2937// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002938void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002939 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002940 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002941 OverloadCandidateSet& CandidateSet,
2942 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002943 FunctionSet Functions;
2944
2945 QualType T1 = Args[0]->getType();
2946 QualType T2;
2947 if (NumArgs > 1)
2948 T2 = Args[1]->getType();
2949
2950 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002951 if (S)
2952 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redlc057f422009-10-23 19:23:15 +00002953 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002954 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2955 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002956 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002957}
2958
2959/// \brief Add overload candidates for overloaded operators that are
2960/// member functions.
2961///
2962/// Add the overloaded operator candidates that are member functions
2963/// for the operator Op that was used in an operator expression such
2964/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2965/// CandidateSet will store the added overload candidates. (C++
2966/// [over.match.oper]).
2967void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2968 SourceLocation OpLoc,
2969 Expr **Args, unsigned NumArgs,
2970 OverloadCandidateSet& CandidateSet,
2971 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002972 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2973
2974 // C++ [over.match.oper]p3:
2975 // For a unary operator @ with an operand of a type whose
2976 // cv-unqualified version is T1, and for a binary operator @ with
2977 // a left operand of a type whose cv-unqualified version is T1 and
2978 // a right operand of a type whose cv-unqualified version is T2,
2979 // three sets of candidate functions, designated member
2980 // candidates, non-member candidates and built-in candidates, are
2981 // constructed as follows:
2982 QualType T1 = Args[0]->getType();
2983 QualType T2;
2984 if (NumArgs > 1)
2985 T2 = Args[1]->getType();
2986
2987 // -- If T1 is a class type, the set of member candidates is the
2988 // result of the qualified lookup of T1::operator@
2989 // (13.3.1.1.1); otherwise, the set of member candidates is
2990 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002991 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002992 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00002993 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002994 return;
Mike Stump11289f42009-09-09 15:08:12 +00002995
John McCall27b18f82009-11-17 02:14:36 +00002996 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
2997 LookupQualifiedName(Operators, T1Rec->getDecl());
2998 Operators.suppressDiagnostics();
2999
Mike Stump11289f42009-09-09 15:08:12 +00003000 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003001 OperEnd = Operators.end();
3002 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003003 ++Oper)
John McCall6e9f8f62009-12-03 04:06:58 +00003004 AddMethodCandidate(*Oper, Args[0]->getType(),
3005 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003006 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003007 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003008}
3009
Douglas Gregora11693b2008-11-12 17:17:38 +00003010/// AddBuiltinCandidate - Add a candidate for a built-in
3011/// operator. ResultTy and ParamTys are the result and parameter types
3012/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003013/// arguments being passed to the candidate. IsAssignmentOperator
3014/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003015/// operator. NumContextualBoolArguments is the number of arguments
3016/// (at the beginning of the argument list) that will be contextually
3017/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003018void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003019 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003020 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003021 bool IsAssignmentOperator,
3022 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003023 // Overload resolution is always an unevaluated context.
3024 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3025
Douglas Gregora11693b2008-11-12 17:17:38 +00003026 // Add this candidate
3027 CandidateSet.push_back(OverloadCandidate());
3028 OverloadCandidate& Candidate = CandidateSet.back();
3029 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003030 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003031 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003032 Candidate.BuiltinTypes.ResultTy = ResultTy;
3033 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3034 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3035
3036 // Determine the implicit conversion sequences for each of the
3037 // arguments.
3038 Candidate.Viable = true;
3039 Candidate.Conversions.resize(NumArgs);
3040 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003041 // C++ [over.match.oper]p4:
3042 // For the built-in assignment operators, conversions of the
3043 // left operand are restricted as follows:
3044 // -- no temporaries are introduced to hold the left operand, and
3045 // -- no user-defined conversions are applied to the left
3046 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003047 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003048 //
3049 // We block these conversions by turning off user-defined
3050 // conversions, since that is the only way that initialization of
3051 // a reference to a non-class type can occur from something that
3052 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003053 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003054 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003055 "Contextual conversion to bool requires bool type");
3056 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3057 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003058 Candidate.Conversions[ArgIdx]
3059 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003060 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003061 /*ForceRValue=*/false,
3062 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003063 }
John McCall0d1da222010-01-12 00:44:57 +00003064 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003065 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003066 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003067 break;
3068 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003069 }
3070}
3071
3072/// BuiltinCandidateTypeSet - A set of types that will be used for the
3073/// candidate operator functions for built-in operators (C++
3074/// [over.built]). The types are separated into pointer types and
3075/// enumeration types.
3076class BuiltinCandidateTypeSet {
3077 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003078 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003079
3080 /// PointerTypes - The set of pointer types that will be used in the
3081 /// built-in candidates.
3082 TypeSet PointerTypes;
3083
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003084 /// MemberPointerTypes - The set of member pointer types that will be
3085 /// used in the built-in candidates.
3086 TypeSet MemberPointerTypes;
3087
Douglas Gregora11693b2008-11-12 17:17:38 +00003088 /// EnumerationTypes - The set of enumeration types that will be
3089 /// used in the built-in candidates.
3090 TypeSet EnumerationTypes;
3091
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003092 /// Sema - The semantic analysis instance where we are building the
3093 /// candidate type set.
3094 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003095
Douglas Gregora11693b2008-11-12 17:17:38 +00003096 /// Context - The AST context in which we will build the type sets.
3097 ASTContext &Context;
3098
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003099 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3100 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003101 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003102
3103public:
3104 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003105 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003106
Mike Stump11289f42009-09-09 15:08:12 +00003107 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003108 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003109
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003110 void AddTypesConvertedFrom(QualType Ty,
3111 SourceLocation Loc,
3112 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003113 bool AllowExplicitConversions,
3114 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003115
3116 /// pointer_begin - First pointer type found;
3117 iterator pointer_begin() { return PointerTypes.begin(); }
3118
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003119 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003120 iterator pointer_end() { return PointerTypes.end(); }
3121
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003122 /// member_pointer_begin - First member pointer type found;
3123 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3124
3125 /// member_pointer_end - Past the last member pointer type found;
3126 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3127
Douglas Gregora11693b2008-11-12 17:17:38 +00003128 /// enumeration_begin - First enumeration type found;
3129 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3130
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003131 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003132 iterator enumeration_end() { return EnumerationTypes.end(); }
3133};
3134
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003135/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003136/// the set of pointer types along with any more-qualified variants of
3137/// that type. For example, if @p Ty is "int const *", this routine
3138/// will add "int const *", "int const volatile *", "int const
3139/// restrict *", and "int const volatile restrict *" to the set of
3140/// pointer types. Returns true if the add of @p Ty itself succeeded,
3141/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003142///
3143/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003144bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003145BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3146 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003147
Douglas Gregora11693b2008-11-12 17:17:38 +00003148 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003149 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003150 return false;
3151
John McCall8ccfcb52009-09-24 19:53:00 +00003152 const PointerType *PointerTy = Ty->getAs<PointerType>();
3153 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003154
John McCall8ccfcb52009-09-24 19:53:00 +00003155 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003156 // Don't add qualified variants of arrays. For one, they're not allowed
3157 // (the qualifier would sink to the element type), and for another, the
3158 // only overload situation where it matters is subscript or pointer +- int,
3159 // and those shouldn't have qualifier variants anyway.
3160 if (PointeeTy->isArrayType())
3161 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003162 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003163 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003164 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003165 bool hasVolatile = VisibleQuals.hasVolatile();
3166 bool hasRestrict = VisibleQuals.hasRestrict();
3167
John McCall8ccfcb52009-09-24 19:53:00 +00003168 // Iterate through all strict supersets of BaseCVR.
3169 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3170 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003171 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3172 // in the types.
3173 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3174 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003175 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3176 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003177 }
3178
3179 return true;
3180}
3181
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003182/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3183/// to the set of pointer types along with any more-qualified variants of
3184/// that type. For example, if @p Ty is "int const *", this routine
3185/// will add "int const *", "int const volatile *", "int const
3186/// restrict *", and "int const volatile restrict *" to the set of
3187/// pointer types. Returns true if the add of @p Ty itself succeeded,
3188/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003189///
3190/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003191bool
3192BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3193 QualType Ty) {
3194 // Insert this type.
3195 if (!MemberPointerTypes.insert(Ty))
3196 return false;
3197
John McCall8ccfcb52009-09-24 19:53:00 +00003198 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3199 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003200
John McCall8ccfcb52009-09-24 19:53:00 +00003201 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003202 // Don't add qualified variants of arrays. For one, they're not allowed
3203 // (the qualifier would sink to the element type), and for another, the
3204 // only overload situation where it matters is subscript or pointer +- int,
3205 // and those shouldn't have qualifier variants anyway.
3206 if (PointeeTy->isArrayType())
3207 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003208 const Type *ClassTy = PointerTy->getClass();
3209
3210 // Iterate through all strict supersets of the pointee type's CVR
3211 // qualifiers.
3212 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3213 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3214 if ((CVR | BaseCVR) != CVR) continue;
3215
3216 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3217 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003218 }
3219
3220 return true;
3221}
3222
Douglas Gregora11693b2008-11-12 17:17:38 +00003223/// AddTypesConvertedFrom - Add each of the types to which the type @p
3224/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003225/// primarily interested in pointer types and enumeration types. We also
3226/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003227/// AllowUserConversions is true if we should look at the conversion
3228/// functions of a class type, and AllowExplicitConversions if we
3229/// should also include the explicit conversion functions of a class
3230/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003231void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003232BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003233 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003234 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003235 bool AllowExplicitConversions,
3236 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003237 // Only deal with canonical types.
3238 Ty = Context.getCanonicalType(Ty);
3239
3240 // Look through reference types; they aren't part of the type of an
3241 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003242 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003243 Ty = RefTy->getPointeeType();
3244
3245 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003246 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003247
Sebastian Redl65ae2002009-11-05 16:36:20 +00003248 // If we're dealing with an array type, decay to the pointer.
3249 if (Ty->isArrayType())
3250 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3251
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003252 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003253 QualType PointeeTy = PointerTy->getPointeeType();
3254
3255 // Insert our type, and its more-qualified variants, into the set
3256 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003257 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003258 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003259 } else if (Ty->isMemberPointerType()) {
3260 // Member pointers are far easier, since the pointee can't be converted.
3261 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3262 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003263 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003264 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003265 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003266 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003267 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003268 // No conversion functions in incomplete types.
3269 return;
3270 }
Mike Stump11289f42009-09-09 15:08:12 +00003271
Douglas Gregora11693b2008-11-12 17:17:38 +00003272 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalld14a8642009-11-21 08:51:07 +00003273 const UnresolvedSet *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003274 = ClassDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00003275 for (UnresolvedSet::iterator I = Conversions->begin(),
3276 E = Conversions->end(); I != E; ++I) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003277
Mike Stump11289f42009-09-09 15:08:12 +00003278 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003279 // about which builtin types we can convert to.
John McCalld14a8642009-11-21 08:51:07 +00003280 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor05155d82009-08-21 23:19:43 +00003281 continue;
3282
John McCalld14a8642009-11-21 08:51:07 +00003283 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003284 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003285 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003286 VisibleQuals);
3287 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003288 }
3289 }
3290 }
3291}
3292
Douglas Gregor84605ae2009-08-24 13:43:27 +00003293/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3294/// the volatile- and non-volatile-qualified assignment operators for the
3295/// given type to the candidate set.
3296static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3297 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003298 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003299 unsigned NumArgs,
3300 OverloadCandidateSet &CandidateSet) {
3301 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003302
Douglas Gregor84605ae2009-08-24 13:43:27 +00003303 // T& operator=(T&, T)
3304 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3305 ParamTypes[1] = T;
3306 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3307 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003308
Douglas Gregor84605ae2009-08-24 13:43:27 +00003309 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3310 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003311 ParamTypes[0]
3312 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003313 ParamTypes[1] = T;
3314 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003315 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003316 }
3317}
Mike Stump11289f42009-09-09 15:08:12 +00003318
Sebastian Redl1054fae2009-10-25 17:03:50 +00003319/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3320/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003321static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3322 Qualifiers VRQuals;
3323 const RecordType *TyRec;
3324 if (const MemberPointerType *RHSMPType =
3325 ArgExpr->getType()->getAs<MemberPointerType>())
3326 TyRec = cast<RecordType>(RHSMPType->getClass());
3327 else
3328 TyRec = ArgExpr->getType()->getAs<RecordType>();
3329 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003330 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003331 VRQuals.addVolatile();
3332 VRQuals.addRestrict();
3333 return VRQuals;
3334 }
3335
3336 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalld14a8642009-11-21 08:51:07 +00003337 const UnresolvedSet *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003338 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003339
John McCalld14a8642009-11-21 08:51:07 +00003340 for (UnresolvedSet::iterator I = Conversions->begin(),
3341 E = Conversions->end(); I != E; ++I) {
3342 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003343 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3344 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3345 CanTy = ResTypeRef->getPointeeType();
3346 // Need to go down the pointer/mempointer chain and add qualifiers
3347 // as see them.
3348 bool done = false;
3349 while (!done) {
3350 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3351 CanTy = ResTypePtr->getPointeeType();
3352 else if (const MemberPointerType *ResTypeMPtr =
3353 CanTy->getAs<MemberPointerType>())
3354 CanTy = ResTypeMPtr->getPointeeType();
3355 else
3356 done = true;
3357 if (CanTy.isVolatileQualified())
3358 VRQuals.addVolatile();
3359 if (CanTy.isRestrictQualified())
3360 VRQuals.addRestrict();
3361 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3362 return VRQuals;
3363 }
3364 }
3365 }
3366 return VRQuals;
3367}
3368
Douglas Gregord08452f2008-11-19 15:42:04 +00003369/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3370/// operator overloads to the candidate set (C++ [over.built]), based
3371/// on the operator @p Op and the arguments given. For example, if the
3372/// operator is a binary '+', this routine might add "int
3373/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003374void
Mike Stump11289f42009-09-09 15:08:12 +00003375Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003376 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003377 Expr **Args, unsigned NumArgs,
3378 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003379 // The set of "promoted arithmetic types", which are the arithmetic
3380 // types are that preserved by promotion (C++ [over.built]p2). Note
3381 // that the first few of these types are the promoted integral
3382 // types; these types need to be first.
3383 // FIXME: What about complex?
3384 const unsigned FirstIntegralType = 0;
3385 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003386 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003387 LastPromotedIntegralType = 13;
3388 const unsigned FirstPromotedArithmeticType = 7,
3389 LastPromotedArithmeticType = 16;
3390 const unsigned NumArithmeticTypes = 16;
3391 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003392 Context.BoolTy, Context.CharTy, Context.WCharTy,
3393// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003394 Context.SignedCharTy, Context.ShortTy,
3395 Context.UnsignedCharTy, Context.UnsignedShortTy,
3396 Context.IntTy, Context.LongTy, Context.LongLongTy,
3397 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3398 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3399 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003400 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3401 "Invalid first promoted integral type");
3402 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3403 == Context.UnsignedLongLongTy &&
3404 "Invalid last promoted integral type");
3405 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3406 "Invalid first promoted arithmetic type");
3407 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3408 == Context.LongDoubleTy &&
3409 "Invalid last promoted arithmetic type");
3410
Douglas Gregora11693b2008-11-12 17:17:38 +00003411 // Find all of the types that the arguments can convert to, but only
3412 // if the operator we're looking at has built-in operator candidates
3413 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003414 Qualifiers VisibleTypeConversionsQuals;
3415 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003416 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3417 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3418
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003419 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003420 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3421 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003422 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003423 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003424 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003425 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003426 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003427 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003428 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003429 true,
3430 (Op == OO_Exclaim ||
3431 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003432 Op == OO_PipePipe),
3433 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003434 }
3435
3436 bool isComparison = false;
3437 switch (Op) {
3438 case OO_None:
3439 case NUM_OVERLOADED_OPERATORS:
3440 assert(false && "Expected an overloaded operator");
3441 break;
3442
Douglas Gregord08452f2008-11-19 15:42:04 +00003443 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003444 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003445 goto UnaryStar;
3446 else
3447 goto BinaryStar;
3448 break;
3449
3450 case OO_Plus: // '+' is either unary or binary
3451 if (NumArgs == 1)
3452 goto UnaryPlus;
3453 else
3454 goto BinaryPlus;
3455 break;
3456
3457 case OO_Minus: // '-' is either unary or binary
3458 if (NumArgs == 1)
3459 goto UnaryMinus;
3460 else
3461 goto BinaryMinus;
3462 break;
3463
3464 case OO_Amp: // '&' is either unary or binary
3465 if (NumArgs == 1)
3466 goto UnaryAmp;
3467 else
3468 goto BinaryAmp;
3469
3470 case OO_PlusPlus:
3471 case OO_MinusMinus:
3472 // C++ [over.built]p3:
3473 //
3474 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3475 // is either volatile or empty, there exist candidate operator
3476 // functions of the form
3477 //
3478 // VQ T& operator++(VQ T&);
3479 // T operator++(VQ T&, int);
3480 //
3481 // C++ [over.built]p4:
3482 //
3483 // For every pair (T, VQ), where T is an arithmetic type other
3484 // than bool, and VQ is either volatile or empty, there exist
3485 // candidate operator functions of the form
3486 //
3487 // VQ T& operator--(VQ T&);
3488 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003489 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003490 Arith < NumArithmeticTypes; ++Arith) {
3491 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003492 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003493 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003494
3495 // Non-volatile version.
3496 if (NumArgs == 1)
3497 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3498 else
3499 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003500 // heuristic to reduce number of builtin candidates in the set.
3501 // Add volatile version only if there are conversions to a volatile type.
3502 if (VisibleTypeConversionsQuals.hasVolatile()) {
3503 // Volatile version
3504 ParamTypes[0]
3505 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3506 if (NumArgs == 1)
3507 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3508 else
3509 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3510 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003511 }
3512
3513 // C++ [over.built]p5:
3514 //
3515 // For every pair (T, VQ), where T is a cv-qualified or
3516 // cv-unqualified object type, and VQ is either volatile or
3517 // empty, there exist candidate operator functions of the form
3518 //
3519 // T*VQ& operator++(T*VQ&);
3520 // T*VQ& operator--(T*VQ&);
3521 // T* operator++(T*VQ&, int);
3522 // T* operator--(T*VQ&, int);
3523 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3524 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3525 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003526 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003527 continue;
3528
Mike Stump11289f42009-09-09 15:08:12 +00003529 QualType ParamTypes[2] = {
3530 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003531 };
Mike Stump11289f42009-09-09 15:08:12 +00003532
Douglas Gregord08452f2008-11-19 15:42:04 +00003533 // Without volatile
3534 if (NumArgs == 1)
3535 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3536 else
3537 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3538
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003539 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3540 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003541 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003542 ParamTypes[0]
3543 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003544 if (NumArgs == 1)
3545 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3546 else
3547 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3548 }
3549 }
3550 break;
3551
3552 UnaryStar:
3553 // C++ [over.built]p6:
3554 // For every cv-qualified or cv-unqualified object type T, there
3555 // exist candidate operator functions of the form
3556 //
3557 // T& operator*(T*);
3558 //
3559 // C++ [over.built]p7:
3560 // For every function type T, there exist candidate operator
3561 // functions of the form
3562 // T& operator*(T*);
3563 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3564 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3565 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003566 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003567 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003568 &ParamTy, Args, 1, CandidateSet);
3569 }
3570 break;
3571
3572 UnaryPlus:
3573 // C++ [over.built]p8:
3574 // For every type T, there exist candidate operator functions of
3575 // the form
3576 //
3577 // T* operator+(T*);
3578 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3579 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3580 QualType ParamTy = *Ptr;
3581 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3582 }
Mike Stump11289f42009-09-09 15:08:12 +00003583
Douglas Gregord08452f2008-11-19 15:42:04 +00003584 // Fall through
3585
3586 UnaryMinus:
3587 // C++ [over.built]p9:
3588 // For every promoted arithmetic type T, there exist candidate
3589 // operator functions of the form
3590 //
3591 // T operator+(T);
3592 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003593 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003594 Arith < LastPromotedArithmeticType; ++Arith) {
3595 QualType ArithTy = ArithmeticTypes[Arith];
3596 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3597 }
3598 break;
3599
3600 case OO_Tilde:
3601 // C++ [over.built]p10:
3602 // For every promoted integral type T, there exist candidate
3603 // operator functions of the form
3604 //
3605 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003606 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003607 Int < LastPromotedIntegralType; ++Int) {
3608 QualType IntTy = ArithmeticTypes[Int];
3609 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3610 }
3611 break;
3612
Douglas Gregora11693b2008-11-12 17:17:38 +00003613 case OO_New:
3614 case OO_Delete:
3615 case OO_Array_New:
3616 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003617 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003618 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003619 break;
3620
3621 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003622 UnaryAmp:
3623 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003624 // C++ [over.match.oper]p3:
3625 // -- For the operator ',', the unary operator '&', or the
3626 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003627 break;
3628
Douglas Gregor84605ae2009-08-24 13:43:27 +00003629 case OO_EqualEqual:
3630 case OO_ExclaimEqual:
3631 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003632 // For every pointer to member type T, there exist candidate operator
3633 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003634 //
3635 // bool operator==(T,T);
3636 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003637 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003638 MemPtr = CandidateTypes.member_pointer_begin(),
3639 MemPtrEnd = CandidateTypes.member_pointer_end();
3640 MemPtr != MemPtrEnd;
3641 ++MemPtr) {
3642 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3643 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3644 }
Mike Stump11289f42009-09-09 15:08:12 +00003645
Douglas Gregor84605ae2009-08-24 13:43:27 +00003646 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003647
Douglas Gregora11693b2008-11-12 17:17:38 +00003648 case OO_Less:
3649 case OO_Greater:
3650 case OO_LessEqual:
3651 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003652 // C++ [over.built]p15:
3653 //
3654 // For every pointer or enumeration type T, there exist
3655 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003656 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003657 // bool operator<(T, T);
3658 // bool operator>(T, T);
3659 // bool operator<=(T, T);
3660 // bool operator>=(T, T);
3661 // bool operator==(T, T);
3662 // bool operator!=(T, T);
3663 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3664 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3665 QualType ParamTypes[2] = { *Ptr, *Ptr };
3666 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3667 }
Mike Stump11289f42009-09-09 15:08:12 +00003668 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003669 = CandidateTypes.enumeration_begin();
3670 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3671 QualType ParamTypes[2] = { *Enum, *Enum };
3672 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3673 }
3674
3675 // Fall through.
3676 isComparison = true;
3677
Douglas Gregord08452f2008-11-19 15:42:04 +00003678 BinaryPlus:
3679 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003680 if (!isComparison) {
3681 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3682
3683 // C++ [over.built]p13:
3684 //
3685 // For every cv-qualified or cv-unqualified object type T
3686 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003687 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003688 // T* operator+(T*, ptrdiff_t);
3689 // T& operator[](T*, ptrdiff_t); [BELOW]
3690 // T* operator-(T*, ptrdiff_t);
3691 // T* operator+(ptrdiff_t, T*);
3692 // T& operator[](ptrdiff_t, T*); [BELOW]
3693 //
3694 // C++ [over.built]p14:
3695 //
3696 // For every T, where T is a pointer to object type, there
3697 // exist candidate operator functions of the form
3698 //
3699 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003700 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003701 = CandidateTypes.pointer_begin();
3702 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3703 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3704
3705 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3706 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3707
3708 if (Op == OO_Plus) {
3709 // T* operator+(ptrdiff_t, T*);
3710 ParamTypes[0] = ParamTypes[1];
3711 ParamTypes[1] = *Ptr;
3712 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3713 } else {
3714 // ptrdiff_t operator-(T, T);
3715 ParamTypes[1] = *Ptr;
3716 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3717 Args, 2, CandidateSet);
3718 }
3719 }
3720 }
3721 // Fall through
3722
Douglas Gregora11693b2008-11-12 17:17:38 +00003723 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003724 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003725 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003726 // C++ [over.built]p12:
3727 //
3728 // For every pair of promoted arithmetic types L and R, there
3729 // exist candidate operator functions of the form
3730 //
3731 // LR operator*(L, R);
3732 // LR operator/(L, R);
3733 // LR operator+(L, R);
3734 // LR operator-(L, R);
3735 // bool operator<(L, R);
3736 // bool operator>(L, R);
3737 // bool operator<=(L, R);
3738 // bool operator>=(L, R);
3739 // bool operator==(L, R);
3740 // bool operator!=(L, R);
3741 //
3742 // where LR is the result of the usual arithmetic conversions
3743 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003744 //
3745 // C++ [over.built]p24:
3746 //
3747 // For every pair of promoted arithmetic types L and R, there exist
3748 // candidate operator functions of the form
3749 //
3750 // LR operator?(bool, L, R);
3751 //
3752 // where LR is the result of the usual arithmetic conversions
3753 // between types L and R.
3754 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003755 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003756 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003757 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003758 Right < LastPromotedArithmeticType; ++Right) {
3759 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003760 QualType Result
3761 = isComparison
3762 ? Context.BoolTy
3763 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003764 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3765 }
3766 }
3767 break;
3768
3769 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003770 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003771 case OO_Caret:
3772 case OO_Pipe:
3773 case OO_LessLess:
3774 case OO_GreaterGreater:
3775 // C++ [over.built]p17:
3776 //
3777 // For every pair of promoted integral types L and R, there
3778 // exist candidate operator functions of the form
3779 //
3780 // LR operator%(L, R);
3781 // LR operator&(L, R);
3782 // LR operator^(L, R);
3783 // LR operator|(L, R);
3784 // L operator<<(L, R);
3785 // L operator>>(L, R);
3786 //
3787 // where LR is the result of the usual arithmetic conversions
3788 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003789 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003790 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003791 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003792 Right < LastPromotedIntegralType; ++Right) {
3793 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3794 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3795 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003796 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003797 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3798 }
3799 }
3800 break;
3801
3802 case OO_Equal:
3803 // C++ [over.built]p20:
3804 //
3805 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003806 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003807 // empty, there exist candidate operator functions of the form
3808 //
3809 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003810 for (BuiltinCandidateTypeSet::iterator
3811 Enum = CandidateTypes.enumeration_begin(),
3812 EnumEnd = CandidateTypes.enumeration_end();
3813 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003814 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003815 CandidateSet);
3816 for (BuiltinCandidateTypeSet::iterator
3817 MemPtr = CandidateTypes.member_pointer_begin(),
3818 MemPtrEnd = CandidateTypes.member_pointer_end();
3819 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003820 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003821 CandidateSet);
3822 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003823
3824 case OO_PlusEqual:
3825 case OO_MinusEqual:
3826 // C++ [over.built]p19:
3827 //
3828 // For every pair (T, VQ), where T is any type and VQ is either
3829 // volatile or empty, there exist candidate operator functions
3830 // of the form
3831 //
3832 // T*VQ& operator=(T*VQ&, T*);
3833 //
3834 // C++ [over.built]p21:
3835 //
3836 // For every pair (T, VQ), where T is a cv-qualified or
3837 // cv-unqualified object type and VQ is either volatile or
3838 // empty, there exist candidate operator functions of the form
3839 //
3840 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3841 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3842 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3843 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3844 QualType ParamTypes[2];
3845 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3846
3847 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003848 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003849 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3850 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003851
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003852 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3853 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003854 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003855 ParamTypes[0]
3856 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003857 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3858 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003859 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003860 }
3861 // Fall through.
3862
3863 case OO_StarEqual:
3864 case OO_SlashEqual:
3865 // C++ [over.built]p18:
3866 //
3867 // For every triple (L, VQ, R), where L is an arithmetic type,
3868 // VQ is either volatile or empty, and R is a promoted
3869 // arithmetic type, there exist candidate operator functions of
3870 // the form
3871 //
3872 // VQ L& operator=(VQ L&, R);
3873 // VQ L& operator*=(VQ L&, R);
3874 // VQ L& operator/=(VQ L&, R);
3875 // VQ L& operator+=(VQ L&, R);
3876 // VQ L& operator-=(VQ L&, R);
3877 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003878 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003879 Right < LastPromotedArithmeticType; ++Right) {
3880 QualType ParamTypes[2];
3881 ParamTypes[1] = ArithmeticTypes[Right];
3882
3883 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003884 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003885 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3886 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003887
3888 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003889 if (VisibleTypeConversionsQuals.hasVolatile()) {
3890 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3891 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3892 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3893 /*IsAssigmentOperator=*/Op == OO_Equal);
3894 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003895 }
3896 }
3897 break;
3898
3899 case OO_PercentEqual:
3900 case OO_LessLessEqual:
3901 case OO_GreaterGreaterEqual:
3902 case OO_AmpEqual:
3903 case OO_CaretEqual:
3904 case OO_PipeEqual:
3905 // C++ [over.built]p22:
3906 //
3907 // For every triple (L, VQ, R), where L is an integral type, VQ
3908 // is either volatile or empty, and R is a promoted integral
3909 // type, there exist candidate operator functions of the form
3910 //
3911 // VQ L& operator%=(VQ L&, R);
3912 // VQ L& operator<<=(VQ L&, R);
3913 // VQ L& operator>>=(VQ L&, R);
3914 // VQ L& operator&=(VQ L&, R);
3915 // VQ L& operator^=(VQ L&, R);
3916 // VQ L& operator|=(VQ L&, R);
3917 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003918 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003919 Right < LastPromotedIntegralType; ++Right) {
3920 QualType ParamTypes[2];
3921 ParamTypes[1] = ArithmeticTypes[Right];
3922
3923 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003924 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003925 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00003926 if (VisibleTypeConversionsQuals.hasVolatile()) {
3927 // Add this built-in operator as a candidate (VQ is 'volatile').
3928 ParamTypes[0] = ArithmeticTypes[Left];
3929 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3930 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3931 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3932 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003933 }
3934 }
3935 break;
3936
Douglas Gregord08452f2008-11-19 15:42:04 +00003937 case OO_Exclaim: {
3938 // C++ [over.operator]p23:
3939 //
3940 // There also exist candidate operator functions of the form
3941 //
Mike Stump11289f42009-09-09 15:08:12 +00003942 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003943 // bool operator&&(bool, bool); [BELOW]
3944 // bool operator||(bool, bool); [BELOW]
3945 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003946 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3947 /*IsAssignmentOperator=*/false,
3948 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003949 break;
3950 }
3951
Douglas Gregora11693b2008-11-12 17:17:38 +00003952 case OO_AmpAmp:
3953 case OO_PipePipe: {
3954 // C++ [over.operator]p23:
3955 //
3956 // There also exist candidate operator functions of the form
3957 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003958 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003959 // bool operator&&(bool, bool);
3960 // bool operator||(bool, bool);
3961 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003962 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3963 /*IsAssignmentOperator=*/false,
3964 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003965 break;
3966 }
3967
3968 case OO_Subscript:
3969 // C++ [over.built]p13:
3970 //
3971 // For every cv-qualified or cv-unqualified object type T there
3972 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003973 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003974 // T* operator+(T*, ptrdiff_t); [ABOVE]
3975 // T& operator[](T*, ptrdiff_t);
3976 // T* operator-(T*, ptrdiff_t); [ABOVE]
3977 // T* operator+(ptrdiff_t, T*); [ABOVE]
3978 // T& operator[](ptrdiff_t, T*);
3979 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3980 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3981 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003982 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003983 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003984
3985 // T& operator[](T*, ptrdiff_t)
3986 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3987
3988 // T& operator[](ptrdiff_t, T*);
3989 ParamTypes[0] = ParamTypes[1];
3990 ParamTypes[1] = *Ptr;
3991 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3992 }
3993 break;
3994
3995 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003996 // C++ [over.built]p11:
3997 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3998 // C1 is the same type as C2 or is a derived class of C2, T is an object
3999 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4000 // there exist candidate operator functions of the form
4001 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4002 // where CV12 is the union of CV1 and CV2.
4003 {
4004 for (BuiltinCandidateTypeSet::iterator Ptr =
4005 CandidateTypes.pointer_begin();
4006 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4007 QualType C1Ty = (*Ptr);
4008 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004009 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004010 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004011 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004012 if (!isa<RecordType>(C1))
4013 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004014 // heuristic to reduce number of builtin candidates in the set.
4015 // Add volatile/restrict version only if there are conversions to a
4016 // volatile/restrict type.
4017 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4018 continue;
4019 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4020 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004021 }
4022 for (BuiltinCandidateTypeSet::iterator
4023 MemPtr = CandidateTypes.member_pointer_begin(),
4024 MemPtrEnd = CandidateTypes.member_pointer_end();
4025 MemPtr != MemPtrEnd; ++MemPtr) {
4026 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4027 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004028 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004029 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4030 break;
4031 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4032 // build CV12 T&
4033 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004034 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4035 T.isVolatileQualified())
4036 continue;
4037 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4038 T.isRestrictQualified())
4039 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004040 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004041 QualType ResultTy = Context.getLValueReferenceType(T);
4042 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4043 }
4044 }
4045 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004046 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004047
4048 case OO_Conditional:
4049 // Note that we don't consider the first argument, since it has been
4050 // contextually converted to bool long ago. The candidates below are
4051 // therefore added as binary.
4052 //
4053 // C++ [over.built]p24:
4054 // For every type T, where T is a pointer or pointer-to-member type,
4055 // there exist candidate operator functions of the form
4056 //
4057 // T operator?(bool, T, T);
4058 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004059 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4060 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4061 QualType ParamTypes[2] = { *Ptr, *Ptr };
4062 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4063 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004064 for (BuiltinCandidateTypeSet::iterator Ptr =
4065 CandidateTypes.member_pointer_begin(),
4066 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4067 QualType ParamTypes[2] = { *Ptr, *Ptr };
4068 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4069 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004070 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004071 }
4072}
4073
Douglas Gregore254f902009-02-04 00:32:51 +00004074/// \brief Add function candidates found via argument-dependent lookup
4075/// to the set of overloading candidates.
4076///
4077/// This routine performs argument-dependent name lookup based on the
4078/// given function name (which may also be an operator name) and adds
4079/// all of the overload candidates found by ADL to the overload
4080/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004081void
Douglas Gregore254f902009-02-04 00:32:51 +00004082Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
4083 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004084 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004085 OverloadCandidateSet& CandidateSet,
4086 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004087 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00004088
Douglas Gregorcabea402009-09-22 15:41:20 +00004089 // FIXME: Should we be trafficking in canonical function decls throughout?
4090
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004091 // Record all of the function candidates that we've already
4092 // added to the overload set, so that we don't add those same
4093 // candidates a second time.
4094 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4095 CandEnd = CandidateSet.end();
4096 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004097 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004098 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004099 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4100 Functions.insert(FunTmpl);
4101 }
Douglas Gregore254f902009-02-04 00:32:51 +00004102
Douglas Gregorcabea402009-09-22 15:41:20 +00004103 // FIXME: Pass in the explicit template arguments?
Sebastian Redlc057f422009-10-23 19:23:15 +00004104 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00004105
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004106 // Erase all of the candidates we already knew about.
4107 // FIXME: This is suboptimal. Is there a better way?
4108 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4109 CandEnd = CandidateSet.end();
4110 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004111 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004112 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004113 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4114 Functions.erase(FunTmpl);
4115 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004116
4117 // For each of the ADL candidates we found, add it to the overload
4118 // set.
4119 for (FunctionSet::iterator Func = Functions.begin(),
4120 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00004121 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00004122 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
John McCall6b51f282009-11-23 01:53:49 +00004123 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004124 continue;
4125
4126 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
4127 false, false, PartialOverloading);
4128 } else
Mike Stump11289f42009-09-09 15:08:12 +00004129 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00004130 ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004131 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004132 }
Douglas Gregore254f902009-02-04 00:32:51 +00004133}
4134
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004135/// isBetterOverloadCandidate - Determines whether the first overload
4136/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004137bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004138Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00004139 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004140 // Define viable functions to be better candidates than non-viable
4141 // functions.
4142 if (!Cand2.Viable)
4143 return Cand1.Viable;
4144 else if (!Cand1.Viable)
4145 return false;
4146
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004147 // C++ [over.match.best]p1:
4148 //
4149 // -- if F is a static member function, ICS1(F) is defined such
4150 // that ICS1(F) is neither better nor worse than ICS1(G) for
4151 // any function G, and, symmetrically, ICS1(G) is neither
4152 // better nor worse than ICS1(F).
4153 unsigned StartArg = 0;
4154 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4155 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004156
Douglas Gregord3cb3562009-07-07 23:38:56 +00004157 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004158 // A viable function F1 is defined to be a better function than another
4159 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004160 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004161 unsigned NumArgs = Cand1.Conversions.size();
4162 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4163 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004164 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004165 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4166 Cand2.Conversions[ArgIdx])) {
4167 case ImplicitConversionSequence::Better:
4168 // Cand1 has a better conversion sequence.
4169 HasBetterConversion = true;
4170 break;
4171
4172 case ImplicitConversionSequence::Worse:
4173 // Cand1 can't be better than Cand2.
4174 return false;
4175
4176 case ImplicitConversionSequence::Indistinguishable:
4177 // Do nothing.
4178 break;
4179 }
4180 }
4181
Mike Stump11289f42009-09-09 15:08:12 +00004182 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004183 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004184 if (HasBetterConversion)
4185 return true;
4186
Mike Stump11289f42009-09-09 15:08:12 +00004187 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004188 // specialization, or, if not that,
4189 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4190 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4191 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004192
4193 // -- F1 and F2 are function template specializations, and the function
4194 // template for F1 is more specialized than the template for F2
4195 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004196 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004197 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4198 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004199 if (FunctionTemplateDecl *BetterTemplate
4200 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4201 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00004202 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4203 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004204 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004205
Douglas Gregora1f013e2008-11-07 22:36:19 +00004206 // -- the context is an initialization by user-defined conversion
4207 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4208 // from the return type of F1 to the destination type (i.e.,
4209 // the type of the entity being initialized) is a better
4210 // conversion sequence than the standard conversion sequence
4211 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004212 if (Cand1.Function && Cand2.Function &&
4213 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004214 isa<CXXConversionDecl>(Cand2.Function)) {
4215 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4216 Cand2.FinalConversion)) {
4217 case ImplicitConversionSequence::Better:
4218 // Cand1 has a better conversion sequence.
4219 return true;
4220
4221 case ImplicitConversionSequence::Worse:
4222 // Cand1 can't be better than Cand2.
4223 return false;
4224
4225 case ImplicitConversionSequence::Indistinguishable:
4226 // Do nothing
4227 break;
4228 }
4229 }
4230
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004231 return false;
4232}
4233
Mike Stump11289f42009-09-09 15:08:12 +00004234/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004235/// within an overload candidate set.
4236///
4237/// \param CandidateSet the set of candidate functions.
4238///
4239/// \param Loc the location of the function name (or operator symbol) for
4240/// which overload resolution occurs.
4241///
Mike Stump11289f42009-09-09 15:08:12 +00004242/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004243/// function, Best points to the candidate function found.
4244///
4245/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004246OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4247 SourceLocation Loc,
4248 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004249 // Find the best viable function.
4250 Best = CandidateSet.end();
4251 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4252 Cand != CandidateSet.end(); ++Cand) {
4253 if (Cand->Viable) {
4254 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4255 Best = Cand;
4256 }
4257 }
4258
4259 // If we didn't find any viable functions, abort.
4260 if (Best == CandidateSet.end())
4261 return OR_No_Viable_Function;
4262
4263 // Make sure that this function is better than every other viable
4264 // function. If not, we have an ambiguity.
4265 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4266 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004267 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004268 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00004269 !isBetterOverloadCandidate(*Best, *Cand)) {
4270 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004271 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004272 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004273 }
Mike Stump11289f42009-09-09 15:08:12 +00004274
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004275 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004276 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004277 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004278 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004279 return OR_Deleted;
4280
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004281 // C++ [basic.def.odr]p2:
4282 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004283 // when referred to from a potentially-evaluated expression. [Note: this
4284 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004285 // (clause 13), user-defined conversions (12.3.2), allocation function for
4286 // placement new (5.3.4), as well as non-default initialization (8.5).
4287 if (Best->Function)
4288 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004289 return OR_Success;
4290}
4291
John McCall53262c92010-01-12 02:15:36 +00004292namespace {
4293
4294enum OverloadCandidateKind {
4295 oc_function,
4296 oc_method,
4297 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004298 oc_function_template,
4299 oc_method_template,
4300 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00004301 oc_implicit_default_constructor,
4302 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004303 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00004304};
4305
John McCalle1ac8d12010-01-13 00:25:19 +00004306OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4307 FunctionDecl *Fn,
4308 std::string &Description) {
4309 bool isTemplate = false;
4310
4311 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4312 isTemplate = true;
4313 Description = S.getTemplateArgumentBindingsText(
4314 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4315 }
John McCallfd0b2f82010-01-06 09:43:14 +00004316
4317 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004318 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004319 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004320
John McCall53262c92010-01-12 02:15:36 +00004321 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4322 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004323 }
4324
4325 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4326 // This actually gets spelled 'candidate function' for now, but
4327 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004328 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004329 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004330
4331 assert(Meth->isCopyAssignment()
4332 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004333 return oc_implicit_copy_assignment;
4334 }
4335
John McCalle1ac8d12010-01-13 00:25:19 +00004336 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00004337}
4338
4339} // end anonymous namespace
4340
4341// Notes the location of an overload candidate.
4342void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00004343 std::string FnDesc;
4344 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4345 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4346 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00004347}
4348
John McCall0d1da222010-01-12 00:44:57 +00004349/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4350/// "lead" diagnostic; it will be given two arguments, the source and
4351/// target types of the conversion.
4352void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4353 SourceLocation CaretLoc,
4354 const PartialDiagnostic &PDiag) {
4355 Diag(CaretLoc, PDiag)
4356 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4357 for (AmbiguousConversionSequence::const_iterator
4358 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4359 NoteOverloadCandidate(*I);
4360 }
John McCall12f97bc2010-01-08 04:41:39 +00004361}
4362
John McCall0d1da222010-01-12 00:44:57 +00004363namespace {
4364
John McCall6a61b522010-01-13 09:16:55 +00004365void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4366 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4367 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00004368 assert(Cand->Function && "for now, candidate must be a function");
4369 FunctionDecl *Fn = Cand->Function;
4370
4371 // There's a conversion slot for the object argument if this is a
4372 // non-constructor method. Note that 'I' corresponds the
4373 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00004374 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00004375 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00004376 if (I == 0)
4377 isObjectArgument = true;
4378 else
4379 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00004380 }
4381
John McCalle1ac8d12010-01-13 00:25:19 +00004382 std::string FnDesc;
4383 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4384
John McCall6a61b522010-01-13 09:16:55 +00004385 Expr *FromExpr = Conv.Bad.FromExpr;
4386 QualType FromTy = Conv.Bad.getFromType();
4387 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00004388
John McCall47000992010-01-14 03:28:57 +00004389 // Do some hand-waving analysis to see if the non-viability is due to a
4390 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4391 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4392 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4393 CToTy = RT->getPointeeType();
4394 else {
4395 // TODO: detect and diagnose the full richness of const mismatches.
4396 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4397 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4398 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4399 }
4400
4401 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4402 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4403 // It is dumb that we have to do this here.
4404 while (isa<ArrayType>(CFromTy))
4405 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4406 while (isa<ArrayType>(CToTy))
4407 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4408
4409 Qualifiers FromQs = CFromTy.getQualifiers();
4410 Qualifiers ToQs = CToTy.getQualifiers();
4411
4412 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4413 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4414 << (unsigned) FnKind << FnDesc
4415 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4416 << FromTy
4417 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4418 << (unsigned) isObjectArgument << I+1;
4419 return;
4420 }
4421
4422 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4423 assert(CVR && "unexpected qualifiers mismatch");
4424
4425 if (isObjectArgument) {
4426 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4427 << (unsigned) FnKind << FnDesc
4428 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4429 << FromTy << (CVR - 1);
4430 } else {
4431 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4432 << (unsigned) FnKind << FnDesc
4433 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4434 << FromTy << (CVR - 1) << I+1;
4435 }
4436 return;
4437 }
4438
4439 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00004440 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4441 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00004442 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00004443 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00004444}
4445
4446void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4447 unsigned NumFormalArgs) {
4448 // TODO: treat calls to a missing default constructor as a special case
4449
4450 FunctionDecl *Fn = Cand->Function;
4451 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4452
4453 unsigned MinParams = Fn->getMinRequiredArguments();
4454
4455 // at least / at most / exactly
4456 unsigned mode, modeCount;
4457 if (NumFormalArgs < MinParams) {
4458 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4459 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4460 mode = 0; // "at least"
4461 else
4462 mode = 2; // "exactly"
4463 modeCount = MinParams;
4464 } else {
4465 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4466 if (MinParams != FnTy->getNumArgs())
4467 mode = 1; // "at most"
4468 else
4469 mode = 2; // "exactly"
4470 modeCount = FnTy->getNumArgs();
4471 }
4472
4473 std::string Description;
4474 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4475
4476 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4477 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00004478}
4479
4480void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4481 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00004482 FunctionDecl *Fn = Cand->Function;
4483
John McCall12f97bc2010-01-08 04:41:39 +00004484 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00004485 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00004486 std::string FnDesc;
4487 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00004488
4489 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00004490 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00004491 return;
John McCall12f97bc2010-01-08 04:41:39 +00004492 }
4493
John McCalle1ac8d12010-01-13 00:25:19 +00004494 // We don't really have anything else to say about viable candidates.
4495 if (Cand->Viable) {
4496 S.NoteOverloadCandidate(Fn);
4497 return;
4498 }
John McCall0d1da222010-01-12 00:44:57 +00004499
John McCall6a61b522010-01-13 09:16:55 +00004500 switch (Cand->FailureKind) {
4501 case ovl_fail_too_many_arguments:
4502 case ovl_fail_too_few_arguments:
4503 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00004504
John McCall6a61b522010-01-13 09:16:55 +00004505 case ovl_fail_bad_deduction:
4506 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004507
John McCall6a61b522010-01-13 09:16:55 +00004508 case ovl_fail_bad_conversion:
4509 for (unsigned I = 0, N = Cand->Conversions.size(); I != N; ++I)
4510 if (Cand->Conversions[I].isBad())
4511 return DiagnoseBadConversion(S, Cand, I);
4512
4513 // FIXME: this currently happens when we're called from SemaInit
4514 // when user-conversion overload fails. Figure out how to handle
4515 // those conditions and diagnose them well.
4516 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004517 }
John McCalld3224162010-01-08 00:58:21 +00004518}
4519
4520void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4521 // Desugar the type of the surrogate down to a function type,
4522 // retaining as many typedefs as possible while still showing
4523 // the function type (and, therefore, its parameter types).
4524 QualType FnType = Cand->Surrogate->getConversionType();
4525 bool isLValueReference = false;
4526 bool isRValueReference = false;
4527 bool isPointer = false;
4528 if (const LValueReferenceType *FnTypeRef =
4529 FnType->getAs<LValueReferenceType>()) {
4530 FnType = FnTypeRef->getPointeeType();
4531 isLValueReference = true;
4532 } else if (const RValueReferenceType *FnTypeRef =
4533 FnType->getAs<RValueReferenceType>()) {
4534 FnType = FnTypeRef->getPointeeType();
4535 isRValueReference = true;
4536 }
4537 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4538 FnType = FnTypePtr->getPointeeType();
4539 isPointer = true;
4540 }
4541 // Desugar down to a function type.
4542 FnType = QualType(FnType->getAs<FunctionType>(), 0);
4543 // Reconstruct the pointer/reference as appropriate.
4544 if (isPointer) FnType = S.Context.getPointerType(FnType);
4545 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
4546 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
4547
4548 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
4549 << FnType;
4550}
4551
4552void NoteBuiltinOperatorCandidate(Sema &S,
4553 const char *Opc,
4554 SourceLocation OpLoc,
4555 OverloadCandidate *Cand) {
4556 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
4557 std::string TypeStr("operator");
4558 TypeStr += Opc;
4559 TypeStr += "(";
4560 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4561 if (Cand->Conversions.size() == 1) {
4562 TypeStr += ")";
4563 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
4564 } else {
4565 TypeStr += ", ";
4566 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4567 TypeStr += ")";
4568 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
4569 }
4570}
4571
4572void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
4573 OverloadCandidate *Cand) {
4574 unsigned NoOperands = Cand->Conversions.size();
4575 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4576 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00004577 if (ICS.isBad()) break; // all meaningless after first invalid
4578 if (!ICS.isAmbiguous()) continue;
4579
4580 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
4581 PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00004582 }
4583}
4584
John McCall3712d9e2010-01-15 23:32:50 +00004585SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
4586 if (Cand->Function)
4587 return Cand->Function->getLocation();
4588 if (Cand->Surrogate)
4589 return Cand->Surrogate->getLocation();
4590 return SourceLocation();
4591}
4592
John McCallad2587a2010-01-12 00:48:53 +00004593struct CompareOverloadCandidatesForDisplay {
4594 Sema &S;
4595 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00004596
4597 bool operator()(const OverloadCandidate *L,
4598 const OverloadCandidate *R) {
4599 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00004600 if (L->Viable) {
4601 if (!R->Viable) return true;
4602
4603 // TODO: introduce a tri-valued comparison for overload
4604 // candidates. Would be more worthwhile if we had a sort
4605 // that could exploit it.
4606 if (S.isBetterOverloadCandidate(*L, *R)) return true;
4607 if (S.isBetterOverloadCandidate(*R, *L)) return false;
4608 } else if (R->Viable)
4609 return false;
John McCall12f97bc2010-01-08 04:41:39 +00004610
John McCall3712d9e2010-01-15 23:32:50 +00004611 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00004612
John McCall3712d9e2010-01-15 23:32:50 +00004613 // Criteria by which we can sort non-viable candidates:
4614 if (!L->Viable) {
4615 // 1. Arity mismatches come after other candidates.
4616 if (L->FailureKind == ovl_fail_too_many_arguments ||
4617 L->FailureKind == ovl_fail_too_few_arguments)
4618 return false;
4619 if (R->FailureKind == ovl_fail_too_many_arguments ||
4620 R->FailureKind == ovl_fail_too_few_arguments)
4621 return true;
John McCall12f97bc2010-01-08 04:41:39 +00004622
John McCall3712d9e2010-01-15 23:32:50 +00004623 // TODO: others?
4624 }
4625
4626 // Sort everything else by location.
4627 SourceLocation LLoc = GetLocationForCandidate(L);
4628 SourceLocation RLoc = GetLocationForCandidate(R);
4629
4630 // Put candidates without locations (e.g. builtins) at the end.
4631 if (LLoc.isInvalid()) return false;
4632 if (RLoc.isInvalid()) return true;
4633
4634 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00004635 }
4636};
4637
John McCalld3224162010-01-08 00:58:21 +00004638} // end anonymous namespace
4639
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004640/// PrintOverloadCandidates - When overload resolution fails, prints
4641/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00004642/// set.
Mike Stump11289f42009-09-09 15:08:12 +00004643void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004644Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00004645 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00004646 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004647 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004648 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00004649 // Sort the candidates by viability and position. Sorting directly would
4650 // be prohibitive, so we make a set of pointers and sort those.
4651 llvm::SmallVector<OverloadCandidate*, 32> Cands;
4652 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
4653 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4654 LastCand = CandidateSet.end();
4655 Cand != LastCand; ++Cand)
4656 if (Cand->Viable || OCD == OCD_AllCandidates)
4657 Cands.push_back(Cand);
John McCallad2587a2010-01-12 00:48:53 +00004658 std::sort(Cands.begin(), Cands.end(),
4659 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00004660
John McCall0d1da222010-01-12 00:44:57 +00004661 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00004662
John McCall12f97bc2010-01-08 04:41:39 +00004663 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
4664 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
4665 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004666
John McCalld3224162010-01-08 00:58:21 +00004667 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00004668 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00004669 else if (Cand->IsSurrogate)
4670 NoteSurrogateCandidate(*this, Cand);
4671
4672 // This a builtin candidate. We do not, in general, want to list
4673 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00004674 else if (Cand->Viable) {
4675 // Generally we only see ambiguities including viable builtin
4676 // operators if overload resolution got screwed up by an
4677 // ambiguous user-defined conversion.
4678 //
4679 // FIXME: It's quite possible for different conversions to see
4680 // different ambiguities, though.
4681 if (!ReportedAmbiguousConversions) {
4682 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
4683 ReportedAmbiguousConversions = true;
4684 }
John McCalld3224162010-01-08 00:58:21 +00004685
John McCall0d1da222010-01-12 00:44:57 +00004686 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00004687 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00004688 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004689 }
4690}
4691
Douglas Gregorcd695e52008-11-10 20:40:00 +00004692/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4693/// an overloaded function (C++ [over.over]), where @p From is an
4694/// expression with overloaded function type and @p ToType is the type
4695/// we're trying to resolve to. For example:
4696///
4697/// @code
4698/// int f(double);
4699/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004700///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004701/// int (*pfd)(double) = f; // selects f(double)
4702/// @endcode
4703///
4704/// This routine returns the resulting FunctionDecl if it could be
4705/// resolved, and NULL otherwise. When @p Complain is true, this
4706/// routine will emit diagnostics if there is an error.
4707FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004708Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004709 bool Complain) {
4710 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004711 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004712 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004713 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004714 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004715 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004716 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004717 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004718 FunctionType = MemTypePtr->getPointeeType();
4719 IsMember = true;
4720 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004721
4722 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00004723 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00004724 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004725 return 0;
4726
4727 // Find the actual overloaded function declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004728
Douglas Gregorcd695e52008-11-10 20:40:00 +00004729 // C++ [over.over]p1:
4730 // [...] [Note: any redundant set of parentheses surrounding the
4731 // overloaded function name is ignored (5.1). ]
4732 Expr *OvlExpr = From->IgnoreParens();
4733
4734 // C++ [over.over]p1:
4735 // [...] The overloaded function name can be preceded by the &
4736 // operator.
4737 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4738 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4739 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4740 }
4741
Anders Carlssonb68b0282009-10-20 22:53:47 +00004742 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004743 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCalld14a8642009-11-21 08:51:07 +00004744
4745 llvm::SmallVector<NamedDecl*,8> Fns;
Anders Carlssonb68b0282009-10-20 22:53:47 +00004746
John McCall10eae182009-11-30 22:42:35 +00004747 // Look into the overloaded expression.
John McCalle66edc12009-11-24 19:00:30 +00004748 if (UnresolvedLookupExpr *UL
John McCalld14a8642009-11-21 08:51:07 +00004749 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4750 Fns.append(UL->decls_begin(), UL->decls_end());
John McCalle66edc12009-11-24 19:00:30 +00004751 if (UL->hasExplicitTemplateArgs()) {
4752 HasExplicitTemplateArgs = true;
4753 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4754 }
John McCall10eae182009-11-30 22:42:35 +00004755 } else if (UnresolvedMemberExpr *ME
4756 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4757 Fns.append(ME->decls_begin(), ME->decls_end());
4758 if (ME->hasExplicitTemplateArgs()) {
4759 HasExplicitTemplateArgs = true;
John McCall6b51f282009-11-23 01:53:49 +00004760 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004761 }
Douglas Gregor9b146582009-07-08 20:55:45 +00004762 }
Mike Stump11289f42009-09-09 15:08:12 +00004763
John McCalld14a8642009-11-21 08:51:07 +00004764 // If we didn't actually find anything, we're done.
4765 if (Fns.empty())
4766 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004767
Douglas Gregorcd695e52008-11-10 20:40:00 +00004768 // Look through all of the overloaded functions, searching for one
4769 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004770 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004771 bool FoundNonTemplateFunction = false;
John McCalld14a8642009-11-21 08:51:07 +00004772 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4773 E = Fns.end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004774 // Look through any using declarations to find the underlying function.
4775 NamedDecl *Fn = (*I)->getUnderlyingDecl();
4776
Douglas Gregorcd695e52008-11-10 20:40:00 +00004777 // C++ [over.over]p3:
4778 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00004779 // targets of type "pointer-to-function" or "reference-to-function."
4780 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004781 // type "pointer-to-member-function."
4782 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004783
Mike Stump11289f42009-09-09 15:08:12 +00004784 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004785 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00004786 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004787 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004788 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004789 // static when converting to member pointer.
4790 if (Method->isStatic() == IsMember)
4791 continue;
4792 } else if (IsMember)
4793 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004794
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004795 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004796 // If the name is a function template, template argument deduction is
4797 // done (14.8.2.2), and if the argument deduction succeeds, the
4798 // resulting template argument list is used to generate a single
4799 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004800 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004801 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00004802 FunctionDecl *Specialization = 0;
4803 TemplateDeductionInfo Info(Context);
4804 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004805 = DeduceTemplateArguments(FunctionTemplate,
4806 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
Douglas Gregor9b146582009-07-08 20:55:45 +00004807 FunctionType, Specialization, Info)) {
4808 // FIXME: make a note of the failed deduction for diagnostics.
4809 (void)Result;
4810 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004811 // FIXME: If the match isn't exact, shouldn't we just drop this as
4812 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00004813 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004814 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004815 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004816 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004817 }
John McCalld14a8642009-11-21 08:51:07 +00004818
4819 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00004820 }
Mike Stump11289f42009-09-09 15:08:12 +00004821
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004822 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004823 // Skip non-static functions when converting to pointer, and static
4824 // when converting to member pointer.
4825 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004826 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00004827
4828 // If we have explicit template arguments, skip non-templates.
4829 if (HasExplicitTemplateArgs)
4830 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004831 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004832 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004833
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004834 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00004835 QualType ResultTy;
4836 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
4837 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
4838 ResultTy)) {
John McCalld14a8642009-11-21 08:51:07 +00004839 Matches.insert(cast<FunctionDecl>(FunDecl->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004840 FoundNonTemplateFunction = true;
4841 }
Mike Stump11289f42009-09-09 15:08:12 +00004842 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004843 }
4844
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004845 // If there were 0 or 1 matches, we're done.
4846 if (Matches.empty())
4847 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004848 else if (Matches.size() == 1) {
4849 FunctionDecl *Result = *Matches.begin();
4850 MarkDeclarationReferenced(From->getLocStart(), Result);
4851 return Result;
4852 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004853
4854 // C++ [over.over]p4:
4855 // If more than one function is selected, [...]
Douglas Gregor05155d82009-08-21 23:19:43 +00004856 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorfae1d712009-09-26 03:56:17 +00004857 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004858 // [...] and any given function template specialization F1 is
4859 // eliminated if the set contains a second function template
4860 // specialization whose function template is more specialized
4861 // than the function template of F1 according to the partial
4862 // ordering rules of 14.5.5.2.
4863
4864 // The algorithm specified above is quadratic. We instead use a
4865 // two-pass algorithm (similar to the one used to identify the
4866 // best viable function in an overload set) that identifies the
4867 // best function template (if it exists).
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004868 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregorfae1d712009-09-26 03:56:17 +00004869 Matches.end());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004870 FunctionDecl *Result =
4871 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4872 TPOC_Other, From->getLocStart(),
4873 PDiag(),
4874 PDiag(diag::err_addr_ovl_ambiguous)
4875 << TemplateMatches[0]->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00004876 PDiag(diag::note_ovl_candidate)
4877 << (unsigned) oc_function_template);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004878 MarkDeclarationReferenced(From->getLocStart(), Result);
4879 return Result;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004880 }
Mike Stump11289f42009-09-09 15:08:12 +00004881
Douglas Gregorfae1d712009-09-26 03:56:17 +00004882 // [...] any function template specializations in the set are
4883 // eliminated if the set also contains a non-template function, [...]
4884 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4885 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4886 if ((*M)->getPrimaryTemplate() == 0)
4887 RemainingMatches.push_back(*M);
4888
Mike Stump11289f42009-09-09 15:08:12 +00004889 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004890 // selected function.
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004891 if (RemainingMatches.size() == 1) {
4892 FunctionDecl *Result = RemainingMatches.front();
4893 MarkDeclarationReferenced(From->getLocStart(), Result);
4894 return Result;
4895 }
Mike Stump11289f42009-09-09 15:08:12 +00004896
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004897 // FIXME: We should probably return the same thing that BestViableFunction
4898 // returns (even if we issue the diagnostics here).
4899 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4900 << RemainingMatches[0]->getDeclName();
4901 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
John McCallfd0b2f82010-01-06 09:43:14 +00004902 NoteOverloadCandidate(RemainingMatches[I]);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004903 return 0;
4904}
4905
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004906/// \brief Given an expression that refers to an overloaded function, try to
4907/// resolve that overloaded function expression down to a single function.
4908///
4909/// This routine can only resolve template-ids that refer to a single function
4910/// template, where that template-id refers to a single template whose template
4911/// arguments are either provided by the template-id or have defaults,
4912/// as described in C++0x [temp.arg.explicit]p3.
4913FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
4914 // C++ [over.over]p1:
4915 // [...] [Note: any redundant set of parentheses surrounding the
4916 // overloaded function name is ignored (5.1). ]
4917 Expr *OvlExpr = From->IgnoreParens();
4918
4919 // C++ [over.over]p1:
4920 // [...] The overloaded function name can be preceded by the &
4921 // operator.
4922 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4923 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4924 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4925 }
4926
4927 bool HasExplicitTemplateArgs = false;
4928 TemplateArgumentListInfo ExplicitTemplateArgs;
4929
4930 llvm::SmallVector<NamedDecl*,8> Fns;
4931
4932 // Look into the overloaded expression.
4933 if (UnresolvedLookupExpr *UL
4934 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4935 Fns.append(UL->decls_begin(), UL->decls_end());
4936 if (UL->hasExplicitTemplateArgs()) {
4937 HasExplicitTemplateArgs = true;
4938 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4939 }
4940 } else if (UnresolvedMemberExpr *ME
4941 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4942 Fns.append(ME->decls_begin(), ME->decls_end());
4943 if (ME->hasExplicitTemplateArgs()) {
4944 HasExplicitTemplateArgs = true;
4945 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4946 }
4947 }
4948
4949 // If we didn't actually find any template-ids, we're done.
4950 if (Fns.empty() || !HasExplicitTemplateArgs)
4951 return 0;
4952
4953 // Look through all of the overloaded functions, searching for one
4954 // whose type matches exactly.
4955 FunctionDecl *Matched = 0;
4956 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4957 E = Fns.end(); I != E; ++I) {
4958 // C++0x [temp.arg.explicit]p3:
4959 // [...] In contexts where deduction is done and fails, or in contexts
4960 // where deduction is not done, if a template argument list is
4961 // specified and it, along with any default template arguments,
4962 // identifies a single function template specialization, then the
4963 // template-id is an lvalue for the function template specialization.
4964 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
4965
4966 // C++ [over.over]p2:
4967 // If the name is a function template, template argument deduction is
4968 // done (14.8.2.2), and if the argument deduction succeeds, the
4969 // resulting template argument list is used to generate a single
4970 // function template specialization, which is added to the set of
4971 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004972 FunctionDecl *Specialization = 0;
4973 TemplateDeductionInfo Info(Context);
4974 if (TemplateDeductionResult Result
4975 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
4976 Specialization, Info)) {
4977 // FIXME: make a note of the failed deduction for diagnostics.
4978 (void)Result;
4979 continue;
4980 }
4981
4982 // Multiple matches; we can't resolve to a single declaration.
4983 if (Matched)
4984 return 0;
4985
4986 Matched = Specialization;
4987 }
4988
4989 return Matched;
4990}
4991
Douglas Gregorcabea402009-09-22 15:41:20 +00004992/// \brief Add a single candidate to the overload set.
4993static void AddOverloadedCallCandidate(Sema &S,
John McCalld14a8642009-11-21 08:51:07 +00004994 NamedDecl *Callee,
John McCall6b51f282009-11-23 01:53:49 +00004995 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004996 Expr **Args, unsigned NumArgs,
4997 OverloadCandidateSet &CandidateSet,
4998 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00004999 if (isa<UsingShadowDecl>(Callee))
5000 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5001
Douglas Gregorcabea402009-09-22 15:41:20 +00005002 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005003 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregorcabea402009-09-22 15:41:20 +00005004 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
5005 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005006 return;
John McCalld14a8642009-11-21 08:51:07 +00005007 }
5008
5009 if (FunctionTemplateDecl *FuncTemplate
5010 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005011 S.AddTemplateOverloadCandidate(FuncTemplate, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005012 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00005013 return;
5014 }
5015
5016 assert(false && "unhandled case in overloaded call candidate");
5017
5018 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00005019}
5020
5021/// \brief Add the overload candidates named by callee and/or found by argument
5022/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00005023void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00005024 Expr **Args, unsigned NumArgs,
5025 OverloadCandidateSet &CandidateSet,
5026 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005027
5028#ifndef NDEBUG
5029 // Verify that ArgumentDependentLookup is consistent with the rules
5030 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00005031 //
Douglas Gregorcabea402009-09-22 15:41:20 +00005032 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5033 // and let Y be the lookup set produced by argument dependent
5034 // lookup (defined as follows). If X contains
5035 //
5036 // -- a declaration of a class member, or
5037 //
5038 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00005039 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00005040 //
5041 // -- a declaration that is neither a function or a function
5042 // template
5043 //
5044 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00005045
John McCall57500772009-12-16 12:17:52 +00005046 if (ULE->requiresADL()) {
5047 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5048 E = ULE->decls_end(); I != E; ++I) {
5049 assert(!(*I)->getDeclContext()->isRecord());
5050 assert(isa<UsingShadowDecl>(*I) ||
5051 !(*I)->getDeclContext()->isFunctionOrMethod());
5052 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00005053 }
5054 }
5055#endif
5056
John McCall57500772009-12-16 12:17:52 +00005057 // It would be nice to avoid this copy.
5058 TemplateArgumentListInfo TABuffer;
5059 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5060 if (ULE->hasExplicitTemplateArgs()) {
5061 ULE->copyTemplateArgumentsInto(TABuffer);
5062 ExplicitTemplateArgs = &TABuffer;
5063 }
5064
5065 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5066 E = ULE->decls_end(); I != E; ++I)
John McCall6b51f282009-11-23 01:53:49 +00005067 AddOverloadedCallCandidate(*this, *I, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005068 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00005069 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00005070
John McCall57500772009-12-16 12:17:52 +00005071 if (ULE->requiresADL())
5072 AddArgumentDependentLookupCandidates(ULE->getName(), Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005073 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005074 CandidateSet,
5075 PartialOverloading);
5076}
John McCalld681c392009-12-16 08:11:27 +00005077
John McCall57500772009-12-16 12:17:52 +00005078static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5079 Expr **Args, unsigned NumArgs) {
5080 Fn->Destroy(SemaRef.Context);
5081 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5082 Args[Arg]->Destroy(SemaRef.Context);
5083 return SemaRef.ExprError();
5084}
5085
John McCalld681c392009-12-16 08:11:27 +00005086/// Attempts to recover from a call where no functions were found.
5087///
5088/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00005089static Sema::OwningExprResult
5090BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn,
5091 UnresolvedLookupExpr *ULE,
5092 SourceLocation LParenLoc,
5093 Expr **Args, unsigned NumArgs,
5094 SourceLocation *CommaLocs,
5095 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00005096
5097 CXXScopeSpec SS;
5098 if (ULE->getQualifier()) {
5099 SS.setScopeRep(ULE->getQualifier());
5100 SS.setRange(ULE->getQualifierRange());
5101 }
5102
John McCall57500772009-12-16 12:17:52 +00005103 TemplateArgumentListInfo TABuffer;
5104 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5105 if (ULE->hasExplicitTemplateArgs()) {
5106 ULE->copyTemplateArgumentsInto(TABuffer);
5107 ExplicitTemplateArgs = &TABuffer;
5108 }
5109
John McCalld681c392009-12-16 08:11:27 +00005110 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5111 Sema::LookupOrdinaryName);
Douglas Gregor598b08f2009-12-31 05:20:13 +00005112 if (SemaRef.DiagnoseEmptyLookup(/*Scope=*/0, SS, R))
John McCall57500772009-12-16 12:17:52 +00005113 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00005114
John McCall57500772009-12-16 12:17:52 +00005115 assert(!R.empty() && "lookup results empty despite recovery");
5116
5117 // Build an implicit member call if appropriate. Just drop the
5118 // casts and such from the call, we don't really care.
5119 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5120 if ((*R.begin())->isCXXClassMember())
5121 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5122 else if (ExplicitTemplateArgs)
5123 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5124 else
5125 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5126
5127 if (NewFn.isInvalid())
5128 return Destroy(SemaRef, Fn, Args, NumArgs);
5129
5130 Fn->Destroy(SemaRef.Context);
5131
5132 // This shouldn't cause an infinite loop because we're giving it
5133 // an expression with non-empty lookup results, which should never
5134 // end up here.
5135 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5136 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5137 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005138}
Douglas Gregorcabea402009-09-22 15:41:20 +00005139
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005140/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00005141/// (which eventually refers to the declaration Func) and the call
5142/// arguments Args/NumArgs, attempt to resolve the function call down
5143/// to a specific function. If overload resolution succeeds, returns
5144/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00005145/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005146/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00005147Sema::OwningExprResult
5148Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE,
5149 SourceLocation LParenLoc,
5150 Expr **Args, unsigned NumArgs,
5151 SourceLocation *CommaLocs,
5152 SourceLocation RParenLoc) {
5153#ifndef NDEBUG
5154 if (ULE->requiresADL()) {
5155 // To do ADL, we must have found an unqualified name.
5156 assert(!ULE->getQualifier() && "qualified name with ADL");
5157
5158 // We don't perform ADL for implicit declarations of builtins.
5159 // Verify that this was correctly set up.
5160 FunctionDecl *F;
5161 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5162 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5163 F->getBuiltinID() && F->isImplicit())
5164 assert(0 && "performing ADL for builtin");
5165
5166 // We don't perform ADL in C.
5167 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5168 }
5169#endif
5170
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005171 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005172
John McCall57500772009-12-16 12:17:52 +00005173 // Add the functions denoted by the callee to the set of candidate
5174 // functions, including those from argument-dependent lookup.
5175 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00005176
5177 // If we found nothing, try to recover.
5178 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5179 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00005180 if (CandidateSet.empty())
5181 return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs,
5182 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005183
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005184 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005185 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00005186 case OR_Success: {
5187 FunctionDecl *FDecl = Best->Function;
5188 Fn = FixOverloadedFunctionReference(Fn, FDecl);
5189 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5190 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005191
5192 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00005193 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005194 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00005195 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005196 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005197 break;
5198
5199 case OR_Ambiguous:
5200 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00005201 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005202 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005203 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005204
5205 case OR_Deleted:
5206 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5207 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00005208 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00005209 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005210 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005211 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005212 }
5213
5214 // Overload resolution failed. Destroy all of the subexpressions and
5215 // return NULL.
5216 Fn->Destroy(Context);
5217 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5218 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00005219 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005220}
5221
John McCall283b9012009-11-22 00:44:51 +00005222static bool IsOverloaded(const Sema::FunctionSet &Functions) {
5223 return Functions.size() > 1 ||
5224 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5225}
5226
Douglas Gregor084d8552009-03-13 23:49:33 +00005227/// \brief Create a unary operation that may resolve to an overloaded
5228/// operator.
5229///
5230/// \param OpLoc The location of the operator itself (e.g., '*').
5231///
5232/// \param OpcIn The UnaryOperator::Opcode that describes this
5233/// operator.
5234///
5235/// \param Functions The set of non-member functions that will be
5236/// considered by overload resolution. The caller needs to build this
5237/// set based on the context using, e.g.,
5238/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5239/// set should not contain any member functions; those will be added
5240/// by CreateOverloadedUnaryOp().
5241///
5242/// \param input The input argument.
5243Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
5244 unsigned OpcIn,
5245 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00005246 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005247 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5248 Expr *Input = (Expr *)input.get();
5249
5250 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5251 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5252 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5253
5254 Expr *Args[2] = { Input, 0 };
5255 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00005256
Douglas Gregor084d8552009-03-13 23:49:33 +00005257 // For post-increment and post-decrement, add the implicit '0' as
5258 // the second argument, so that we know this is a post-increment or
5259 // post-decrement.
5260 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5261 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00005262 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00005263 SourceLocation());
5264 NumArgs = 2;
5265 }
5266
5267 if (Input->isTypeDependent()) {
John McCalld14a8642009-11-21 08:51:07 +00005268 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005269 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5270 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00005271 /*ADL*/ true, IsOverloaded(Functions));
Mike Stump11289f42009-09-09 15:08:12 +00005272 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00005273 FuncEnd = Functions.end();
5274 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00005275 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00005276
Douglas Gregor084d8552009-03-13 23:49:33 +00005277 input.release();
5278 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5279 &Args[0], NumArgs,
5280 Context.DependentTy,
5281 OpLoc));
5282 }
5283
5284 // Build an empty overload set.
5285 OverloadCandidateSet CandidateSet;
5286
5287 // Add the candidates from the given function set.
5288 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
5289
5290 // Add operator candidates that are member functions.
5291 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5292
5293 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005294 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00005295
5296 // Perform overload resolution.
5297 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005298 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005299 case OR_Success: {
5300 // We found a built-in operator or an overloaded operator.
5301 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00005302
Douglas Gregor084d8552009-03-13 23:49:33 +00005303 if (FnDecl) {
5304 // We matched an overloaded operator. Build a call to that
5305 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00005306
Douglas Gregor084d8552009-03-13 23:49:33 +00005307 // Convert the arguments.
5308 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
5309 if (PerformObjectArgumentInitialization(Input, Method))
5310 return ExprError();
5311 } else {
5312 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00005313 OwningExprResult InputInit
5314 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005315 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00005316 SourceLocation(),
5317 move(input));
5318 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00005319 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005320
Douglas Gregore6600372009-12-23 17:40:29 +00005321 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005322 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00005323 }
5324
5325 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005326 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005327
Douglas Gregor084d8552009-03-13 23:49:33 +00005328 // Build the actual expression node.
5329 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5330 SourceLocation());
5331 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005332
Douglas Gregor084d8552009-03-13 23:49:33 +00005333 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00005334 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005335 ExprOwningPtr<CallExpr> TheCall(this,
5336 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00005337 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005338
5339 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5340 FnDecl))
5341 return ExprError();
5342
5343 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00005344 } else {
5345 // We matched a built-in operator. Convert the arguments, then
5346 // break out so that we will build the appropriate built-in
5347 // operator node.
5348 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005349 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00005350 return ExprError();
5351
5352 break;
5353 }
5354 }
5355
5356 case OR_No_Viable_Function:
5357 // No viable function; fall through to handling this as a
5358 // built-in operator, which will produce an error message for us.
5359 break;
5360
5361 case OR_Ambiguous:
5362 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5363 << UnaryOperator::getOpcodeStr(Opc)
5364 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005365 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005366 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005367 return ExprError();
5368
5369 case OR_Deleted:
5370 Diag(OpLoc, diag::err_ovl_deleted_oper)
5371 << Best->Function->isDeleted()
5372 << UnaryOperator::getOpcodeStr(Opc)
5373 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005374 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00005375 return ExprError();
5376 }
5377
5378 // Either we found no viable overloaded operator or we matched a
5379 // built-in operator. In either case, fall through to trying to
5380 // build a built-in operation.
5381 input.release();
5382 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5383}
5384
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005385/// \brief Create a binary operation that may resolve to an overloaded
5386/// operator.
5387///
5388/// \param OpLoc The location of the operator itself (e.g., '+').
5389///
5390/// \param OpcIn The BinaryOperator::Opcode that describes this
5391/// operator.
5392///
5393/// \param Functions The set of non-member functions that will be
5394/// considered by overload resolution. The caller needs to build this
5395/// set based on the context using, e.g.,
5396/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5397/// set should not contain any member functions; those will be added
5398/// by CreateOverloadedBinOp().
5399///
5400/// \param LHS Left-hand argument.
5401/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00005402Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005403Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005404 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005405 FunctionSet &Functions,
5406 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005407 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00005408 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005409
5410 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5411 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5412 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5413
5414 // If either side is type-dependent, create an appropriate dependent
5415 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00005416 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00005417 if (Functions.empty()) {
5418 // If there are no functions to store, just build a dependent
5419 // BinaryOperator or CompoundAssignment.
5420 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5421 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5422 Context.DependentTy, OpLoc));
5423
5424 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5425 Context.DependentTy,
5426 Context.DependentTy,
5427 Context.DependentTy,
5428 OpLoc));
5429 }
5430
John McCalld14a8642009-11-21 08:51:07 +00005431 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005432 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5433 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00005434 /* ADL */ true, IsOverloaded(Functions));
John McCalld14a8642009-11-21 08:51:07 +00005435
Mike Stump11289f42009-09-09 15:08:12 +00005436 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005437 FuncEnd = Functions.end();
5438 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00005439 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00005440
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005441 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00005442 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005443 Context.DependentTy,
5444 OpLoc));
5445 }
5446
5447 // If this is the .* operator, which is not overloadable, just
5448 // create a built-in binary operator.
5449 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00005450 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005451
Sebastian Redl6a96bf72009-11-18 23:10:33 +00005452 // If this is the assignment operator, we only perform overload resolution
5453 // if the left-hand side is a class or enumeration type. This is actually
5454 // a hack. The standard requires that we do overload resolution between the
5455 // various built-in candidates, but as DR507 points out, this can lead to
5456 // problems. So we do it this way, which pretty much follows what GCC does.
5457 // Note that we go the traditional code path for compound assignment forms.
5458 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00005459 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005460
Douglas Gregor084d8552009-03-13 23:49:33 +00005461 // Build an empty overload set.
5462 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005463
5464 // Add the candidates from the given function set.
5465 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
5466
5467 // Add operator candidates that are member functions.
5468 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5469
5470 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005471 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005472
5473 // Perform overload resolution.
5474 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005475 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005476 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005477 // We found a built-in operator or an overloaded operator.
5478 FunctionDecl *FnDecl = Best->Function;
5479
5480 if (FnDecl) {
5481 // We matched an overloaded operator. Build a call to that
5482 // operator.
5483
5484 // Convert the arguments.
5485 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005486 OwningExprResult Arg1
5487 = PerformCopyInitialization(
5488 InitializedEntity::InitializeParameter(
5489 FnDecl->getParamDecl(0)),
5490 SourceLocation(),
5491 Owned(Args[1]));
5492 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005493 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005494
5495 if (PerformObjectArgumentInitialization(Args[0], Method))
5496 return ExprError();
5497
5498 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005499 } else {
5500 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005501 OwningExprResult Arg0
5502 = PerformCopyInitialization(
5503 InitializedEntity::InitializeParameter(
5504 FnDecl->getParamDecl(0)),
5505 SourceLocation(),
5506 Owned(Args[0]));
5507 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005508 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005509
5510 OwningExprResult Arg1
5511 = PerformCopyInitialization(
5512 InitializedEntity::InitializeParameter(
5513 FnDecl->getParamDecl(1)),
5514 SourceLocation(),
5515 Owned(Args[1]));
5516 if (Arg1.isInvalid())
5517 return ExprError();
5518 Args[0] = LHS = Arg0.takeAs<Expr>();
5519 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005520 }
5521
5522 // Determine the result type
5523 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00005524 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005525 ResultTy = ResultTy.getNonReferenceType();
5526
5527 // Build the actual expression node.
5528 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00005529 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005530 UsualUnaryConversions(FnExpr);
5531
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005532 ExprOwningPtr<CXXOperatorCallExpr>
5533 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5534 Args, 2, ResultTy,
5535 OpLoc));
5536
5537 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5538 FnDecl))
5539 return ExprError();
5540
5541 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005542 } else {
5543 // We matched a built-in operator. Convert the arguments, then
5544 // break out so that we will build the appropriate built-in
5545 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00005546 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005547 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00005548 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005549 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005550 return ExprError();
5551
5552 break;
5553 }
5554 }
5555
Douglas Gregor66950a32009-09-30 21:46:01 +00005556 case OR_No_Viable_Function: {
5557 // C++ [over.match.oper]p9:
5558 // If the operator is the operator , [...] and there are no
5559 // viable functions, then the operator is assumed to be the
5560 // built-in operator and interpreted according to clause 5.
5561 if (Opc == BinaryOperator::Comma)
5562 break;
5563
Sebastian Redl027de2a2009-05-21 11:50:50 +00005564 // For class as left operand for assignment or compound assigment operator
5565 // do not fall through to handling in built-in, but report that no overloaded
5566 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00005567 OwningExprResult Result = ExprError();
5568 if (Args[0]->getType()->isRecordType() &&
5569 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00005570 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5571 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005572 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00005573 } else {
5574 // No viable function; try to create a built-in operation, which will
5575 // produce an error. Then, show the non-viable candidates.
5576 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00005577 }
Douglas Gregor66950a32009-09-30 21:46:01 +00005578 assert(Result.isInvalid() &&
5579 "C++ binary operator overloading is missing candidates!");
5580 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00005581 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005582 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00005583 return move(Result);
5584 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005585
5586 case OR_Ambiguous:
5587 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5588 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005589 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005590 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005591 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005592 return ExprError();
5593
5594 case OR_Deleted:
5595 Diag(OpLoc, diag::err_ovl_deleted_oper)
5596 << Best->Function->isDeleted()
5597 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005598 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005599 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005600 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00005601 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005602
Douglas Gregor66950a32009-09-30 21:46:01 +00005603 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00005604 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005605}
5606
Sebastian Redladba46e2009-10-29 20:17:01 +00005607Action::OwningExprResult
5608Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5609 SourceLocation RLoc,
5610 ExprArg Base, ExprArg Idx) {
5611 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5612 static_cast<Expr*>(Idx.get()) };
5613 DeclarationName OpName =
5614 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5615
5616 // If either side is type-dependent, create an appropriate dependent
5617 // expression.
5618 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5619
John McCalld14a8642009-11-21 08:51:07 +00005620 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005621 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5622 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00005623 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00005624 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00005625
5626 Base.release();
5627 Idx.release();
5628 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5629 Args, 2,
5630 Context.DependentTy,
5631 RLoc));
5632 }
5633
5634 // Build an empty overload set.
5635 OverloadCandidateSet CandidateSet;
5636
5637 // Subscript can only be overloaded as a member function.
5638
5639 // Add operator candidates that are member functions.
5640 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5641
5642 // Add builtin operator candidates.
5643 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5644
5645 // Perform overload resolution.
5646 OverloadCandidateSet::iterator Best;
5647 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5648 case OR_Success: {
5649 // We found a built-in operator or an overloaded operator.
5650 FunctionDecl *FnDecl = Best->Function;
5651
5652 if (FnDecl) {
5653 // We matched an overloaded operator. Build a call to that
5654 // operator.
5655
5656 // Convert the arguments.
5657 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5658 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5659 PerformCopyInitialization(Args[1],
5660 FnDecl->getParamDecl(0)->getType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005661 AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00005662 return ExprError();
5663
5664 // Determine the result type
5665 QualType ResultTy
5666 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5667 ResultTy = ResultTy.getNonReferenceType();
5668
5669 // Build the actual expression node.
5670 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5671 LLoc);
5672 UsualUnaryConversions(FnExpr);
5673
5674 Base.release();
5675 Idx.release();
5676 ExprOwningPtr<CXXOperatorCallExpr>
5677 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5678 FnExpr, Args, 2,
5679 ResultTy, RLoc));
5680
5681 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5682 FnDecl))
5683 return ExprError();
5684
5685 return MaybeBindToTemporary(TheCall.release());
5686 } else {
5687 // We matched a built-in operator. Convert the arguments, then
5688 // break out so that we will build the appropriate built-in
5689 // operator node.
5690 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005691 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00005692 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005693 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00005694 return ExprError();
5695
5696 break;
5697 }
5698 }
5699
5700 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00005701 if (CandidateSet.empty())
5702 Diag(LLoc, diag::err_ovl_no_oper)
5703 << Args[0]->getType() << /*subscript*/ 0
5704 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5705 else
5706 Diag(LLoc, diag::err_ovl_no_viable_subscript)
5707 << Args[0]->getType()
5708 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005709 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00005710 "[]", LLoc);
5711 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00005712 }
5713
5714 case OR_Ambiguous:
5715 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5716 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005717 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00005718 "[]", LLoc);
5719 return ExprError();
5720
5721 case OR_Deleted:
5722 Diag(LLoc, diag::err_ovl_deleted_oper)
5723 << Best->Function->isDeleted() << "[]"
5724 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005725 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00005726 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00005727 return ExprError();
5728 }
5729
5730 // We matched a built-in operator; build it.
5731 Base.release();
5732 Idx.release();
5733 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5734 Owned(Args[1]), RLoc);
5735}
5736
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005737/// BuildCallToMemberFunction - Build a call to a member
5738/// function. MemExpr is the expression that refers to the member
5739/// function (and includes the object parameter), Args/NumArgs are the
5740/// arguments to the function call (not including the object
5741/// parameter). The caller needs to validate that the member
5742/// expression refers to a member function or an overloaded member
5743/// function.
John McCall2d74de92009-12-01 22:10:20 +00005744Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00005745Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5746 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005747 unsigned NumArgs, SourceLocation *CommaLocs,
5748 SourceLocation RParenLoc) {
5749 // Dig out the member expression. This holds both the object
5750 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00005751 Expr *NakedMemExpr = MemExprE->IgnoreParens();
5752
John McCall10eae182009-11-30 22:42:35 +00005753 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005754 CXXMethodDecl *Method = 0;
John McCall10eae182009-11-30 22:42:35 +00005755 if (isa<MemberExpr>(NakedMemExpr)) {
5756 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00005757 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5758 } else {
5759 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
John McCall2d74de92009-12-01 22:10:20 +00005760
John McCall6e9f8f62009-12-03 04:06:58 +00005761 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00005762
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005763 // Add overload candidates
5764 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00005765
John McCall2d74de92009-12-01 22:10:20 +00005766 // FIXME: avoid copy.
5767 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5768 if (UnresExpr->hasExplicitTemplateArgs()) {
5769 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5770 TemplateArgs = &TemplateArgsBuffer;
5771 }
5772
John McCall10eae182009-11-30 22:42:35 +00005773 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
5774 E = UnresExpr->decls_end(); I != E; ++I) {
5775
John McCall6e9f8f62009-12-03 04:06:58 +00005776 NamedDecl *Func = *I;
5777 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
5778 if (isa<UsingShadowDecl>(Func))
5779 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
5780
John McCall10eae182009-11-30 22:42:35 +00005781 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00005782 // If explicit template arguments were provided, we can't call a
5783 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00005784 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00005785 continue;
5786
John McCall6e9f8f62009-12-03 04:06:58 +00005787 AddMethodCandidate(Method, ActingDC, ObjectType, Args, NumArgs,
5788 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005789 } else {
John McCall10eae182009-11-30 22:42:35 +00005790 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall6e9f8f62009-12-03 04:06:58 +00005791 ActingDC, TemplateArgs,
5792 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005793 CandidateSet,
5794 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005795 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005796 }
Mike Stump11289f42009-09-09 15:08:12 +00005797
John McCall10eae182009-11-30 22:42:35 +00005798 DeclarationName DeclName = UnresExpr->getMemberName();
5799
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005800 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00005801 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005802 case OR_Success:
5803 Method = cast<CXXMethodDecl>(Best->Function);
5804 break;
5805
5806 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00005807 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005808 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005809 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005810 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005811 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005812 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005813
5814 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00005815 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005816 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005817 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005818 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005819 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005820
5821 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00005822 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00005823 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00005824 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005825 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005826 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005827 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005828 }
5829
Douglas Gregor51c538b2009-11-20 19:42:02 +00005830 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCall2d74de92009-12-01 22:10:20 +00005831
John McCall2d74de92009-12-01 22:10:20 +00005832 // If overload resolution picked a static member, build a
5833 // non-member call based on that function.
5834 if (Method->isStatic()) {
5835 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
5836 Args, NumArgs, RParenLoc);
5837 }
5838
John McCall10eae182009-11-30 22:42:35 +00005839 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005840 }
5841
5842 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00005843 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00005844 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00005845 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005846 Method->getResultType().getNonReferenceType(),
5847 RParenLoc));
5848
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005849 // Check for a valid return type.
5850 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5851 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00005852 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005853
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005854 // Convert the object argument (for a non-static member function call).
John McCall2d74de92009-12-01 22:10:20 +00005855 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00005856 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005857 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCall2d74de92009-12-01 22:10:20 +00005858 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005859 MemExpr->setBase(ObjectArg);
5860
5861 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005862 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00005863 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005864 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00005865 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005866
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005867 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00005868 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00005869
John McCall2d74de92009-12-01 22:10:20 +00005870 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005871}
5872
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005873/// BuildCallToObjectOfClassType - Build a call to an object of class
5874/// type (C++ [over.call.object]), which can end up invoking an
5875/// overloaded function call operator (@c operator()) or performing a
5876/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00005877Sema::ExprResult
5878Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00005879 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005880 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00005881 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005882 SourceLocation RParenLoc) {
5883 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005884 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00005885
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005886 // C++ [over.call.object]p1:
5887 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00005888 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005889 // candidate functions includes at least the function call
5890 // operators of T. The function call operators of T are obtained by
5891 // ordinary lookup of the name operator() in the context of
5892 // (E).operator().
5893 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00005894 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005895
5896 if (RequireCompleteType(LParenLoc, Object->getType(),
5897 PartialDiagnostic(diag::err_incomplete_object_call)
5898 << Object->getSourceRange()))
5899 return true;
5900
John McCall27b18f82009-11-17 02:14:36 +00005901 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5902 LookupQualifiedName(R, Record->getDecl());
5903 R.suppressDiagnostics();
5904
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005905 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00005906 Oper != OperEnd; ++Oper) {
John McCall6e9f8f62009-12-03 04:06:58 +00005907 AddMethodCandidate(*Oper, Object->getType(), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005908 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00005909 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005910
Douglas Gregorab7897a2008-11-19 22:57:39 +00005911 // C++ [over.call.object]p2:
5912 // In addition, for each conversion function declared in T of the
5913 // form
5914 //
5915 // operator conversion-type-id () cv-qualifier;
5916 //
5917 // where cv-qualifier is the same cv-qualification as, or a
5918 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00005919 // denotes the type "pointer to function of (P1,...,Pn) returning
5920 // R", or the type "reference to pointer to function of
5921 // (P1,...,Pn) returning R", or the type "reference to function
5922 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00005923 // is also considered as a candidate function. Similarly,
5924 // surrogate call functions are added to the set of candidate
5925 // functions for each conversion function declared in an
5926 // accessible base class provided the function is not hidden
5927 // within T by another intervening declaration.
John McCalld14a8642009-11-21 08:51:07 +00005928 const UnresolvedSet *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00005929 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00005930 for (UnresolvedSet::iterator I = Conversions->begin(),
5931 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00005932 NamedDecl *D = *I;
5933 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5934 if (isa<UsingShadowDecl>(D))
5935 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5936
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005937 // Skip over templated conversion functions; they aren't
5938 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00005939 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005940 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005941
John McCall6e9f8f62009-12-03 04:06:58 +00005942 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00005943
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005944 // Strip the reference type (if any) and then the pointer type (if
5945 // any) to get down to what might be a function type.
5946 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5947 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5948 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005949
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005950 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall6e9f8f62009-12-03 04:06:58 +00005951 AddSurrogateCandidate(Conv, ActingContext, Proto,
5952 Object->getType(), Args, NumArgs,
5953 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00005954 }
Mike Stump11289f42009-09-09 15:08:12 +00005955
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005956 // Perform overload resolution.
5957 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005958 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005959 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00005960 // Overload resolution succeeded; we'll build the appropriate call
5961 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005962 break;
5963
5964 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00005965 if (CandidateSet.empty())
5966 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
5967 << Object->getType() << /*call*/ 1
5968 << Object->getSourceRange();
5969 else
5970 Diag(Object->getSourceRange().getBegin(),
5971 diag::err_ovl_no_viable_object_call)
5972 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005973 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005974 break;
5975
5976 case OR_Ambiguous:
5977 Diag(Object->getSourceRange().getBegin(),
5978 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005979 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005980 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005981 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005982
5983 case OR_Deleted:
5984 Diag(Object->getSourceRange().getBegin(),
5985 diag::err_ovl_deleted_object_call)
5986 << Best->Function->isDeleted()
5987 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005988 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005989 break;
Mike Stump11289f42009-09-09 15:08:12 +00005990 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005991
Douglas Gregorab7897a2008-11-19 22:57:39 +00005992 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005993 // We had an error; delete all of the subexpressions and return
5994 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00005995 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005996 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00005997 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005998 return true;
5999 }
6000
Douglas Gregorab7897a2008-11-19 22:57:39 +00006001 if (Best->Function == 0) {
6002 // Since there is no function declaration, this is one of the
6003 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00006004 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00006005 = cast<CXXConversionDecl>(
6006 Best->Conversions[0].UserDefined.ConversionFunction);
6007
6008 // We selected one of the surrogate functions that converts the
6009 // object parameter to a function pointer. Perform the conversion
6010 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006011
6012 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006013 // and then call it.
Eli Friedmana958a012009-12-09 04:52:43 +00006014 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006015
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006016 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006017 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
6018 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006019 }
6020
6021 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6022 // that calls this method, using Object for the implicit object
6023 // parameter and passing along the remaining arguments.
6024 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00006025 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006026
6027 unsigned NumArgsInProto = Proto->getNumArgs();
6028 unsigned NumArgsToCheck = NumArgs;
6029
6030 // Build the full argument list for the method call (the
6031 // implicit object parameter is placed at the beginning of the
6032 // list).
6033 Expr **MethodArgs;
6034 if (NumArgs < NumArgsInProto) {
6035 NumArgsToCheck = NumArgsInProto;
6036 MethodArgs = new Expr*[NumArgsInProto + 1];
6037 } else {
6038 MethodArgs = new Expr*[NumArgs + 1];
6039 }
6040 MethodArgs[0] = Object;
6041 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6042 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00006043
6044 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00006045 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006046 UsualUnaryConversions(NewFn);
6047
6048 // Once we've built TheCall, all of the expressions are properly
6049 // owned.
6050 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006051 ExprOwningPtr<CXXOperatorCallExpr>
6052 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006053 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00006054 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006055 delete [] MethodArgs;
6056
Anders Carlsson3d5829c2009-10-13 21:49:31 +00006057 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6058 Method))
6059 return true;
6060
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006061 // We may have default arguments. If so, we need to allocate more
6062 // slots in the call for them.
6063 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00006064 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006065 else if (NumArgs > NumArgsInProto)
6066 NumArgsToCheck = NumArgsInProto;
6067
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006068 bool IsError = false;
6069
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006070 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006071 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006072 TheCall->setArg(0, Object);
6073
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006074
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006075 // Check the argument types.
6076 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006077 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006078 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006079 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00006080
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006081 // Pass the argument.
6082 QualType ProtoArgType = Proto->getArgType(i);
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006083 IsError |= PerformCopyInitialization(Arg, ProtoArgType, AA_Passing);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006084 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00006085 OwningExprResult DefArg
6086 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6087 if (DefArg.isInvalid()) {
6088 IsError = true;
6089 break;
6090 }
6091
6092 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006093 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006094
6095 TheCall->setArg(i + 1, Arg);
6096 }
6097
6098 // If this is a variadic call, handle args passed through "...".
6099 if (Proto->isVariadic()) {
6100 // Promote the arguments (C99 6.5.2.2p7).
6101 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6102 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006103 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006104 TheCall->setArg(i + 1, Arg);
6105 }
6106 }
6107
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006108 if (IsError) return true;
6109
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006110 if (CheckFunctionCall(Method, TheCall.get()))
6111 return true;
6112
Anders Carlsson1c83deb2009-08-16 03:53:54 +00006113 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006114}
6115
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006116/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00006117/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006118/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00006119Sema::OwningExprResult
6120Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6121 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006122 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00006123
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006124 // C++ [over.ref]p1:
6125 //
6126 // [...] An expression x->m is interpreted as (x.operator->())->m
6127 // for a class object x of type T if T::operator->() exists and if
6128 // the operator is selected as the best match function by the
6129 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006130 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
6131 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006132 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00006133
Eli Friedman132e70b2009-11-18 01:28:03 +00006134 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
6135 PDiag(diag::err_typecheck_incomplete_tag)
6136 << Base->getSourceRange()))
6137 return ExprError();
6138
John McCall27b18f82009-11-17 02:14:36 +00006139 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6140 LookupQualifiedName(R, BaseRecord->getDecl());
6141 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00006142
6143 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00006144 Oper != OperEnd; ++Oper) {
6145 NamedDecl *D = *Oper;
6146 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6147 if (isa<UsingShadowDecl>(D))
6148 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6149
6150 AddMethodCandidate(cast<CXXMethodDecl>(D), ActingContext,
6151 Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006152 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00006153 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006154
6155 // Perform overload resolution.
6156 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006157 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006158 case OR_Success:
6159 // Overload resolution succeeded; we'll build the call below.
6160 break;
6161
6162 case OR_No_Viable_Function:
6163 if (CandidateSet.empty())
6164 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00006165 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006166 else
6167 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00006168 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006169 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006170 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006171
6172 case OR_Ambiguous:
6173 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00006174 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006175 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006176 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006177
6178 case OR_Deleted:
6179 Diag(OpLoc, diag::err_ovl_deleted_oper)
6180 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00006181 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006182 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006183 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006184 }
6185
6186 // Convert the object parameter.
6187 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00006188 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00006189 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00006190
6191 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00006192 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006193
6194 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00006195 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6196 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006197 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006198
6199 QualType ResultTy = Method->getResultType().getNonReferenceType();
6200 ExprOwningPtr<CXXOperatorCallExpr>
6201 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6202 &Base, 1, ResultTy, OpLoc));
6203
6204 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6205 Method))
6206 return ExprError();
6207 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006208}
6209
Douglas Gregorcd695e52008-11-10 20:40:00 +00006210/// FixOverloadedFunctionReference - E is an expression that refers to
6211/// a C++ overloaded function (possibly with some parentheses and
6212/// perhaps a '&' around it). We have resolved the overloaded function
6213/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006214/// refer (possibly indirectly) to Fn. Returns the new expr.
6215Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006216 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor51c538b2009-11-20 19:42:02 +00006217 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
6218 if (SubExpr == PE->getSubExpr())
6219 return PE->Retain();
6220
6221 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6222 }
6223
6224 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6225 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00006226 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00006227 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00006228 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00006229 if (SubExpr == ICE->getSubExpr())
6230 return ICE->Retain();
6231
6232 return new (Context) ImplicitCastExpr(ICE->getType(),
6233 ICE->getCastKind(),
6234 SubExpr,
6235 ICE->isLvalueCast());
6236 }
6237
6238 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00006239 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00006240 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006241 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6242 if (Method->isStatic()) {
6243 // Do nothing: static member functions aren't any different
6244 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00006245 } else {
John McCalle66edc12009-11-24 19:00:30 +00006246 // Fix the sub expression, which really has to be an
6247 // UnresolvedLookupExpr holding an overloaded member function
6248 // or template.
John McCalld14a8642009-11-21 08:51:07 +00006249 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6250 if (SubExpr == UnOp->getSubExpr())
6251 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00006252
John McCalld14a8642009-11-21 08:51:07 +00006253 assert(isa<DeclRefExpr>(SubExpr)
6254 && "fixed to something other than a decl ref");
6255 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6256 && "fixed to a member ref with no nested name qualifier");
6257
6258 // We have taken the address of a pointer to member
6259 // function. Perform the computation here so that we get the
6260 // appropriate pointer to member type.
6261 QualType ClassType
6262 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6263 QualType MemPtrType
6264 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6265
6266 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6267 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006268 }
6269 }
Douglas Gregor51c538b2009-11-20 19:42:02 +00006270 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6271 if (SubExpr == UnOp->getSubExpr())
6272 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006273
Douglas Gregor51c538b2009-11-20 19:42:02 +00006274 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6275 Context.getPointerType(SubExpr->getType()),
6276 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00006277 }
John McCalld14a8642009-11-21 08:51:07 +00006278
6279 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00006280 // FIXME: avoid copy.
6281 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00006282 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00006283 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6284 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00006285 }
6286
John McCalld14a8642009-11-21 08:51:07 +00006287 return DeclRefExpr::Create(Context,
6288 ULE->getQualifier(),
6289 ULE->getQualifierRange(),
6290 Fn,
6291 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006292 Fn->getType(),
6293 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00006294 }
6295
John McCall10eae182009-11-30 22:42:35 +00006296 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00006297 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00006298 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6299 if (MemExpr->hasExplicitTemplateArgs()) {
6300 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6301 TemplateArgs = &TemplateArgsBuffer;
6302 }
John McCall6b51f282009-11-23 01:53:49 +00006303
John McCall2d74de92009-12-01 22:10:20 +00006304 Expr *Base;
6305
6306 // If we're filling in
6307 if (MemExpr->isImplicitAccess()) {
6308 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6309 return DeclRefExpr::Create(Context,
6310 MemExpr->getQualifier(),
6311 MemExpr->getQualifierRange(),
6312 Fn,
6313 MemExpr->getMemberLoc(),
6314 Fn->getType(),
6315 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00006316 } else {
6317 SourceLocation Loc = MemExpr->getMemberLoc();
6318 if (MemExpr->getQualifier())
6319 Loc = MemExpr->getQualifierRange().getBegin();
6320 Base = new (Context) CXXThisExpr(Loc,
6321 MemExpr->getBaseType(),
6322 /*isImplicit=*/true);
6323 }
John McCall2d74de92009-12-01 22:10:20 +00006324 } else
6325 Base = MemExpr->getBase()->Retain();
6326
6327 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006328 MemExpr->isArrow(),
6329 MemExpr->getQualifier(),
6330 MemExpr->getQualifierRange(),
6331 Fn,
John McCall6b51f282009-11-23 01:53:49 +00006332 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006333 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006334 Fn->getType());
6335 }
6336
Douglas Gregor51c538b2009-11-20 19:42:02 +00006337 assert(false && "Invalid reference to overloaded function");
6338 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00006339}
6340
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006341Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
6342 FunctionDecl *Fn) {
6343 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
6344}
6345
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006346} // end namespace clang