blob: ffcf8d4609ac85cc04f7ddaea532364866d62f53 [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 McCall0d1da222010-01-12 00:44:57 +0000496 } else if (UserDefResult == OR_Ambiguous) {
497 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 McCall6e9f8f62009-12-03 04:06:58 +00002194Sema::TryObjectArgumentInitialization(QualType FromType,
2195 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.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002211 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002212 FromType = PT->getPointeeType();
2213
2214 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002215
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002216 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002217 // where X is the class of which the function is a member
2218 // (C++ [over.match.funcs]p4). However, when finding an implicit
2219 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002220 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002221 // (C++ [over.match.funcs]p5). We perform a simplified version of
2222 // reference binding here, that allows class rvalues to bind to
2223 // non-constant references.
2224
2225 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2226 // with the implicit object parameter (C++ [over.match.funcs]p5).
2227 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002228 if (ImplicitParamType.getCVRQualifiers()
2229 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002230 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
2231 ICS.Bad.init(BadConversionSequence::bad_qualifiers, FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002232 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002233 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002234
2235 // Check that we have either the same type or a derived type. It
2236 // affects the conversion rank.
2237 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002238 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor436424c2008-11-18 23:14:02 +00002239 ICS.Standard.Second = ICK_Identity;
2240 else if (IsDerivedFrom(FromType, ClassType))
2241 ICS.Standard.Second = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002242 else {
2243 ICS.Bad.init(BadConversionSequence::unrelated_class, FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002244 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002245 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002246
2247 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002248 ICS.setStandard();
2249 ICS.Standard.setFromType(FromType);
2250 ICS.Standard.setToType(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002251 ICS.Standard.ReferenceBinding = true;
2252 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002253 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002254 return ICS;
2255}
2256
2257/// PerformObjectArgumentInitialization - Perform initialization of
2258/// the implicit object parameter for the given Method with the given
2259/// expression.
2260bool
2261Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002262 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002263 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002264 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002265
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002266 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002267 FromRecordType = PT->getPointeeType();
2268 DestType = Method->getThisType(Context);
2269 } else {
2270 FromRecordType = From->getType();
2271 DestType = ImplicitParamRecordType;
2272 }
2273
John McCall6e9f8f62009-12-03 04:06:58 +00002274 // Note that we always use the true parent context when performing
2275 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002276 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002277 = TryObjectArgumentInitialization(From->getType(), Method,
2278 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002279 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002280 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002281 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002282 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002283
Douglas Gregor436424c2008-11-18 23:14:02 +00002284 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002285 CheckDerivedToBaseConversion(FromRecordType,
2286 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002287 From->getSourceRange().getBegin(),
2288 From->getSourceRange()))
2289 return true;
2290
Mike Stump11289f42009-09-09 15:08:12 +00002291 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002292 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002293 return false;
2294}
2295
Douglas Gregor5fb53972009-01-14 15:45:31 +00002296/// TryContextuallyConvertToBool - Attempt to contextually convert the
2297/// expression From to bool (C++0x [conv]p3).
2298ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002299 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002300 // FIXME: Are these flags correct?
2301 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002302 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002303 /*ForceRValue=*/false,
2304 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002305}
2306
2307/// PerformContextuallyConvertToBool - Perform a contextual conversion
2308/// of the expression From to bool (C++0x [conv]p3).
2309bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2310 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00002311 if (!ICS.isBad())
2312 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002313
Fariborz Jahanian76197412009-11-18 18:26:29 +00002314 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002315 return Diag(From->getSourceRange().getBegin(),
2316 diag::err_typecheck_bool_condition)
2317 << From->getType() << From->getSourceRange();
2318 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002319}
2320
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002321/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002322/// candidate functions, using the given function call arguments. If
2323/// @p SuppressUserConversions, then don't allow user-defined
2324/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002325/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2326/// hacky way to implement the overloading rules for elidable copy
2327/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002328///
2329/// \para PartialOverloading true if we are performing "partial" overloading
2330/// based on an incomplete set of function arguments. This feature is used by
2331/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002332void
2333Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002334 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002335 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002336 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002337 bool ForceRValue,
2338 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002339 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002340 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002341 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002342 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002343 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002344
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002345 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002346 if (!isa<CXXConstructorDecl>(Method)) {
2347 // If we get here, it's because we're calling a member function
2348 // that is named without a member access expression (e.g.,
2349 // "this->f") that was either written explicitly or created
2350 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002351 // function, e.g., X::f(). We use an empty type for the implied
2352 // object argument (C++ [over.call.func]p3), and the acting context
2353 // is irrelevant.
2354 AddMethodCandidate(Method, Method->getParent(),
2355 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002356 SuppressUserConversions, ForceRValue);
2357 return;
2358 }
2359 // We treat a constructor like a non-member function, since its object
2360 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002361 }
2362
Douglas Gregorff7028a2009-11-13 23:59:09 +00002363 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002364 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002365
Douglas Gregor27381f32009-11-23 12:27:39 +00002366 // Overload resolution is always an unevaluated context.
2367 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2368
Douglas Gregorffe14e32009-11-14 01:20:54 +00002369 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2370 // C++ [class.copy]p3:
2371 // A member function template is never instantiated to perform the copy
2372 // of a class object to an object of its class type.
2373 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2374 if (NumArgs == 1 &&
2375 Constructor->isCopyConstructorLikeSpecialization() &&
2376 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2377 return;
2378 }
2379
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002380 // Add this candidate
2381 CandidateSet.push_back(OverloadCandidate());
2382 OverloadCandidate& Candidate = CandidateSet.back();
2383 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002384 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002385 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002386 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002387
2388 unsigned NumArgsInProto = Proto->getNumArgs();
2389
2390 // (C++ 13.3.2p2): A candidate function having fewer than m
2391 // parameters is viable only if it has an ellipsis in its parameter
2392 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002393 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2394 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002395 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002396 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002397 return;
2398 }
2399
2400 // (C++ 13.3.2p2): A candidate function having more than m parameters
2401 // is viable only if the (m+1)st parameter has a default argument
2402 // (8.3.6). For the purposes of overload resolution, the
2403 // parameter list is truncated on the right, so that there are
2404 // exactly m parameters.
2405 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002406 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002407 // Not enough arguments.
2408 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002409 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002410 return;
2411 }
2412
2413 // Determine the implicit conversion sequences for each of the
2414 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002415 Candidate.Conversions.resize(NumArgs);
2416 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2417 if (ArgIdx < NumArgsInProto) {
2418 // (C++ 13.3.2p3): for F to be a viable function, there shall
2419 // exist for each argument an implicit conversion sequence
2420 // (13.3.3.1) that converts that argument to the corresponding
2421 // parameter of F.
2422 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002423 Candidate.Conversions[ArgIdx]
2424 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002425 SuppressUserConversions, ForceRValue,
2426 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002427 if (Candidate.Conversions[ArgIdx].isBad()) {
2428 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002429 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00002430 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00002431 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002432 } else {
2433 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2434 // argument for which there is no corresponding parameter is
2435 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002436 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002437 }
2438 }
2439}
2440
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002441/// \brief Add all of the function declarations in the given function set to
2442/// the overload canddiate set.
2443void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2444 Expr **Args, unsigned NumArgs,
2445 OverloadCandidateSet& CandidateSet,
2446 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002447 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002448 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002449 F != FEnd; ++F) {
John McCall6e9f8f62009-12-03 04:06:58 +00002450 // FIXME: using declarations
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002451 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2452 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2453 AddMethodCandidate(cast<CXXMethodDecl>(FD),
John McCall6e9f8f62009-12-03 04:06:58 +00002454 cast<CXXMethodDecl>(FD)->getParent(),
2455 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002456 CandidateSet, SuppressUserConversions);
2457 else
2458 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2459 SuppressUserConversions);
2460 } else {
2461 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2462 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2463 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2464 AddMethodTemplateCandidate(FunTmpl,
John McCall6e9f8f62009-12-03 04:06:58 +00002465 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002466 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002467 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002468 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002469 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002470 else
2471 AddTemplateOverloadCandidate(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00002472 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002473 Args, NumArgs, CandidateSet,
2474 SuppressUserConversions);
2475 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002476 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002477}
2478
John McCallf0f1cf02009-11-17 07:50:12 +00002479/// AddMethodCandidate - Adds a named decl (which is some kind of
2480/// method) as a method candidate to the given overload set.
John McCall6e9f8f62009-12-03 04:06:58 +00002481void Sema::AddMethodCandidate(NamedDecl *Decl,
2482 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002483 Expr **Args, unsigned NumArgs,
2484 OverloadCandidateSet& CandidateSet,
2485 bool SuppressUserConversions, bool ForceRValue) {
John McCall6e9f8f62009-12-03 04:06:58 +00002486 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002487
2488 if (isa<UsingShadowDecl>(Decl))
2489 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2490
2491 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2492 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2493 "Expected a member function template");
John McCall6e9f8f62009-12-03 04:06:58 +00002494 AddMethodTemplateCandidate(TD, ActingContext, /*ExplicitArgs*/ 0,
2495 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002496 CandidateSet,
2497 SuppressUserConversions,
2498 ForceRValue);
2499 } else {
John McCall6e9f8f62009-12-03 04:06:58 +00002500 AddMethodCandidate(cast<CXXMethodDecl>(Decl), ActingContext,
2501 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002502 CandidateSet, SuppressUserConversions, ForceRValue);
2503 }
2504}
2505
Douglas Gregor436424c2008-11-18 23:14:02 +00002506/// AddMethodCandidate - Adds the given C++ member function to the set
2507/// of candidate functions, using the given function call arguments
2508/// and the object argument (@c Object). For example, in a call
2509/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2510/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2511/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002512/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2513/// a slightly hacky way to implement the overloading rules for elidable copy
2514/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002515void
John McCall6e9f8f62009-12-03 04:06:58 +00002516Sema::AddMethodCandidate(CXXMethodDecl *Method, CXXRecordDecl *ActingContext,
2517 QualType ObjectType, Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002518 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002519 bool SuppressUserConversions, bool ForceRValue) {
2520 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002521 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002522 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002523 assert(!isa<CXXConstructorDecl>(Method) &&
2524 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002525
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002526 if (!CandidateSet.isNewCandidate(Method))
2527 return;
2528
Douglas Gregor27381f32009-11-23 12:27:39 +00002529 // Overload resolution is always an unevaluated context.
2530 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2531
Douglas Gregor436424c2008-11-18 23:14:02 +00002532 // Add this candidate
2533 CandidateSet.push_back(OverloadCandidate());
2534 OverloadCandidate& Candidate = CandidateSet.back();
2535 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002536 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002537 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002538
2539 unsigned NumArgsInProto = Proto->getNumArgs();
2540
2541 // (C++ 13.3.2p2): A candidate function having fewer than m
2542 // parameters is viable only if it has an ellipsis in its parameter
2543 // list (8.3.5).
2544 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2545 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002546 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002547 return;
2548 }
2549
2550 // (C++ 13.3.2p2): A candidate function having more than m parameters
2551 // is viable only if the (m+1)st parameter has a default argument
2552 // (8.3.6). For the purposes of overload resolution, the
2553 // parameter list is truncated on the right, so that there are
2554 // exactly m parameters.
2555 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2556 if (NumArgs < MinRequiredArgs) {
2557 // Not enough arguments.
2558 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002559 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00002560 return;
2561 }
2562
2563 Candidate.Viable = true;
2564 Candidate.Conversions.resize(NumArgs + 1);
2565
John McCall6e9f8f62009-12-03 04:06:58 +00002566 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002567 // The implicit object argument is ignored.
2568 Candidate.IgnoreObjectArgument = true;
2569 else {
2570 // Determine the implicit conversion sequence for the object
2571 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002572 Candidate.Conversions[0]
2573 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002574 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002575 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002576 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002577 return;
2578 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002579 }
2580
2581 // Determine the implicit conversion sequences for each of the
2582 // arguments.
2583 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2584 if (ArgIdx < NumArgsInProto) {
2585 // (C++ 13.3.2p3): for F to be a viable function, there shall
2586 // exist for each argument an implicit conversion sequence
2587 // (13.3.3.1) that converts that argument to the corresponding
2588 // parameter of F.
2589 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002590 Candidate.Conversions[ArgIdx + 1]
2591 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002592 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002593 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00002594 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002595 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002596 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00002597 break;
2598 }
2599 } else {
2600 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2601 // argument for which there is no corresponding parameter is
2602 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002603 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00002604 }
2605 }
2606}
2607
Douglas Gregor97628d62009-08-21 00:16:32 +00002608/// \brief Add a C++ member function template as a candidate to the candidate
2609/// set, using template argument deduction to produce an appropriate member
2610/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002611void
Douglas Gregor97628d62009-08-21 00:16:32 +00002612Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall6e9f8f62009-12-03 04:06:58 +00002613 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00002614 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00002615 QualType ObjectType,
2616 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002617 OverloadCandidateSet& CandidateSet,
2618 bool SuppressUserConversions,
2619 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002620 if (!CandidateSet.isNewCandidate(MethodTmpl))
2621 return;
2622
Douglas Gregor97628d62009-08-21 00:16:32 +00002623 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002624 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002625 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002626 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002627 // candidate functions in the usual way.113) A given name can refer to one
2628 // or more function templates and also to a set of overloaded non-template
2629 // functions. In such a case, the candidate functions generated from each
2630 // function template are combined with the set of non-template candidate
2631 // functions.
2632 TemplateDeductionInfo Info(Context);
2633 FunctionDecl *Specialization = 0;
2634 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002635 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002636 Args, NumArgs, Specialization, Info)) {
2637 // FIXME: Record what happened with template argument deduction, so
2638 // that we can give the user a beautiful diagnostic.
2639 (void)Result;
2640 return;
2641 }
Mike Stump11289f42009-09-09 15:08:12 +00002642
Douglas Gregor97628d62009-08-21 00:16:32 +00002643 // Add the function template specialization produced by template argument
2644 // deduction as a candidate.
2645 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002646 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002647 "Specialization is not a member function?");
John McCall6e9f8f62009-12-03 04:06:58 +00002648 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), ActingContext,
2649 ObjectType, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002650 CandidateSet, SuppressUserConversions, ForceRValue);
2651}
2652
Douglas Gregor05155d82009-08-21 23:19:43 +00002653/// \brief Add a C++ function template specialization as a candidate
2654/// in the candidate set, using template argument deduction to produce
2655/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002656void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002657Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00002658 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002659 Expr **Args, unsigned NumArgs,
2660 OverloadCandidateSet& CandidateSet,
2661 bool SuppressUserConversions,
2662 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002663 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2664 return;
2665
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002666 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002667 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002668 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002669 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002670 // candidate functions in the usual way.113) A given name can refer to one
2671 // or more function templates and also to a set of overloaded non-template
2672 // functions. In such a case, the candidate functions generated from each
2673 // function template are combined with the set of non-template candidate
2674 // functions.
2675 TemplateDeductionInfo Info(Context);
2676 FunctionDecl *Specialization = 0;
2677 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002678 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002679 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002680 // FIXME: Record what happened with template argument deduction, so
2681 // that we can give the user a beautiful diagnostic.
John McCalld681c392009-12-16 08:11:27 +00002682 (void) Result;
2683
2684 CandidateSet.push_back(OverloadCandidate());
2685 OverloadCandidate &Candidate = CandidateSet.back();
2686 Candidate.Function = FunctionTemplate->getTemplatedDecl();
2687 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002688 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00002689 Candidate.IsSurrogate = false;
2690 Candidate.IgnoreObjectArgument = false;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002691 return;
2692 }
Mike Stump11289f42009-09-09 15:08:12 +00002693
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002694 // Add the function template specialization produced by template argument
2695 // deduction as a candidate.
2696 assert(Specialization && "Missing function template specialization?");
2697 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2698 SuppressUserConversions, ForceRValue);
2699}
Mike Stump11289f42009-09-09 15:08:12 +00002700
Douglas Gregora1f013e2008-11-07 22:36:19 +00002701/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002702/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002703/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002704/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002705/// (which may or may not be the same type as the type that the
2706/// conversion function produces).
2707void
2708Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall6e9f8f62009-12-03 04:06:58 +00002709 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002710 Expr *From, QualType ToType,
2711 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002712 assert(!Conversion->getDescribedFunctionTemplate() &&
2713 "Conversion function templates use AddTemplateConversionCandidate");
2714
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002715 if (!CandidateSet.isNewCandidate(Conversion))
2716 return;
2717
Douglas Gregor27381f32009-11-23 12:27:39 +00002718 // Overload resolution is always an unevaluated context.
2719 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2720
Douglas Gregora1f013e2008-11-07 22:36:19 +00002721 // Add this candidate
2722 CandidateSet.push_back(OverloadCandidate());
2723 OverloadCandidate& Candidate = CandidateSet.back();
2724 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002725 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002726 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002727 Candidate.FinalConversion.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00002728 Candidate.FinalConversion.setFromType(Conversion->getConversionType());
2729 Candidate.FinalConversion.setToType(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00002730
Douglas Gregor436424c2008-11-18 23:14:02 +00002731 // Determine the implicit conversion sequence for the implicit
2732 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002733 Candidate.Viable = true;
2734 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00002735 Candidate.Conversions[0]
2736 = TryObjectArgumentInitialization(From->getType(), Conversion,
2737 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002738 // Conversion functions to a different type in the base class is visible in
2739 // the derived class. So, a derived to base conversion should not participate
2740 // in overload resolution.
2741 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2742 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00002743 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002744 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002745 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002746 return;
2747 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002748
2749 // We won't go through a user-define type conversion function to convert a
2750 // derived to base as such conversions are given Conversion Rank. They only
2751 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2752 QualType FromCanon
2753 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2754 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2755 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2756 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002757 Candidate.FailureKind = ovl_fail_bad_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002758 return;
2759 }
2760
Douglas Gregora1f013e2008-11-07 22:36:19 +00002761
2762 // To determine what the conversion from the result of calling the
2763 // conversion function to the type we're eventually trying to
2764 // convert to (ToType), we need to synthesize a call to the
2765 // conversion function and attempt copy initialization from it. This
2766 // makes sure that we get the right semantics with respect to
2767 // lvalues/rvalues and the type. Fortunately, we can allocate this
2768 // call on the stack and we don't need its arguments to be
2769 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002770 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002771 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00002772 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002773 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002774 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002775
2776 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002777 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2778 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002779 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002780 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002781 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002782 ImplicitConversionSequence ICS =
2783 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002784 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002785 /*ForceRValue=*/false,
2786 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002787
John McCall0d1da222010-01-12 00:44:57 +00002788 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002789 case ImplicitConversionSequence::StandardConversion:
2790 Candidate.FinalConversion = ICS.Standard;
2791 break;
2792
2793 case ImplicitConversionSequence::BadConversion:
2794 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002795 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002796 break;
2797
2798 default:
Mike Stump11289f42009-09-09 15:08:12 +00002799 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002800 "Can only end up with a standard conversion sequence or failure");
2801 }
2802}
2803
Douglas Gregor05155d82009-08-21 23:19:43 +00002804/// \brief Adds a conversion function template specialization
2805/// candidate to the overload set, using template argument deduction
2806/// to deduce the template arguments of the conversion function
2807/// template from the type that we are converting to (C++
2808/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002809void
Douglas Gregor05155d82009-08-21 23:19:43 +00002810Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6e9f8f62009-12-03 04:06:58 +00002811 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00002812 Expr *From, QualType ToType,
2813 OverloadCandidateSet &CandidateSet) {
2814 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2815 "Only conversion function templates permitted here");
2816
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002817 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2818 return;
2819
Douglas Gregor05155d82009-08-21 23:19:43 +00002820 TemplateDeductionInfo Info(Context);
2821 CXXConversionDecl *Specialization = 0;
2822 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002823 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002824 Specialization, Info)) {
2825 // FIXME: Record what happened with template argument deduction, so
2826 // that we can give the user a beautiful diagnostic.
2827 (void)Result;
2828 return;
2829 }
Mike Stump11289f42009-09-09 15:08:12 +00002830
Douglas Gregor05155d82009-08-21 23:19:43 +00002831 // Add the conversion function template specialization produced by
2832 // template argument deduction as a candidate.
2833 assert(Specialization && "Missing function template specialization?");
John McCall6e9f8f62009-12-03 04:06:58 +00002834 AddConversionCandidate(Specialization, ActingDC, From, ToType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00002835}
2836
Douglas Gregorab7897a2008-11-19 22:57:39 +00002837/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2838/// converts the given @c Object to a function pointer via the
2839/// conversion function @c Conversion, and then attempts to call it
2840/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2841/// the type of function that we'll eventually be calling.
2842void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall6e9f8f62009-12-03 04:06:58 +00002843 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002844 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00002845 QualType ObjectType,
2846 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002847 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002848 if (!CandidateSet.isNewCandidate(Conversion))
2849 return;
2850
Douglas Gregor27381f32009-11-23 12:27:39 +00002851 // Overload resolution is always an unevaluated context.
2852 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2853
Douglas Gregorab7897a2008-11-19 22:57:39 +00002854 CandidateSet.push_back(OverloadCandidate());
2855 OverloadCandidate& Candidate = CandidateSet.back();
2856 Candidate.Function = 0;
2857 Candidate.Surrogate = Conversion;
2858 Candidate.Viable = true;
2859 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002860 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002861 Candidate.Conversions.resize(NumArgs + 1);
2862
2863 // Determine the implicit conversion sequence for the implicit
2864 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002865 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00002866 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00002867 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00002868 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002869 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002870 return;
2871 }
2872
2873 // The first conversion is actually a user-defined conversion whose
2874 // first conversion is ObjectInit's standard conversion (which is
2875 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00002876 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00002877 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002878 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002879 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002880 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002881 = Candidate.Conversions[0].UserDefined.Before;
2882 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2883
Mike Stump11289f42009-09-09 15:08:12 +00002884 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002885 unsigned NumArgsInProto = Proto->getNumArgs();
2886
2887 // (C++ 13.3.2p2): A candidate function having fewer than m
2888 // parameters is viable only if it has an ellipsis in its parameter
2889 // list (8.3.5).
2890 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2891 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002892 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002893 return;
2894 }
2895
2896 // Function types don't have any default arguments, so just check if
2897 // we have enough arguments.
2898 if (NumArgs < NumArgsInProto) {
2899 // Not enough arguments.
2900 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002901 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002902 return;
2903 }
2904
2905 // Determine the implicit conversion sequences for each of the
2906 // arguments.
2907 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2908 if (ArgIdx < NumArgsInProto) {
2909 // (C++ 13.3.2p3): for F to be a viable function, there shall
2910 // exist for each argument an implicit conversion sequence
2911 // (13.3.3.1) that converts that argument to the corresponding
2912 // parameter of F.
2913 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002914 Candidate.Conversions[ArgIdx + 1]
2915 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002916 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002917 /*ForceRValue=*/false,
2918 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00002919 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00002920 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002921 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002922 break;
2923 }
2924 } else {
2925 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2926 // argument for which there is no corresponding parameter is
2927 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00002928 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00002929 }
2930 }
2931}
2932
Mike Stump87c57ac2009-05-16 07:39:55 +00002933// FIXME: This will eventually be removed, once we've migrated all of the
2934// operator overloading logic over to the scheme used by binary operators, which
2935// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002936void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002937 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002938 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002939 OverloadCandidateSet& CandidateSet,
2940 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002941 FunctionSet Functions;
2942
2943 QualType T1 = Args[0]->getType();
2944 QualType T2;
2945 if (NumArgs > 1)
2946 T2 = Args[1]->getType();
2947
2948 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002949 if (S)
2950 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redlc057f422009-10-23 19:23:15 +00002951 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002952 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2953 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002954 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002955}
2956
2957/// \brief Add overload candidates for overloaded operators that are
2958/// member functions.
2959///
2960/// Add the overloaded operator candidates that are member functions
2961/// for the operator Op that was used in an operator expression such
2962/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2963/// CandidateSet will store the added overload candidates. (C++
2964/// [over.match.oper]).
2965void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2966 SourceLocation OpLoc,
2967 Expr **Args, unsigned NumArgs,
2968 OverloadCandidateSet& CandidateSet,
2969 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002970 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2971
2972 // C++ [over.match.oper]p3:
2973 // For a unary operator @ with an operand of a type whose
2974 // cv-unqualified version is T1, and for a binary operator @ with
2975 // a left operand of a type whose cv-unqualified version is T1 and
2976 // a right operand of a type whose cv-unqualified version is T2,
2977 // three sets of candidate functions, designated member
2978 // candidates, non-member candidates and built-in candidates, are
2979 // constructed as follows:
2980 QualType T1 = Args[0]->getType();
2981 QualType T2;
2982 if (NumArgs > 1)
2983 T2 = Args[1]->getType();
2984
2985 // -- If T1 is a class type, the set of member candidates is the
2986 // result of the qualified lookup of T1::operator@
2987 // (13.3.1.1.1); otherwise, the set of member candidates is
2988 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002989 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002990 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00002991 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002992 return;
Mike Stump11289f42009-09-09 15:08:12 +00002993
John McCall27b18f82009-11-17 02:14:36 +00002994 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
2995 LookupQualifiedName(Operators, T1Rec->getDecl());
2996 Operators.suppressDiagnostics();
2997
Mike Stump11289f42009-09-09 15:08:12 +00002998 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002999 OperEnd = Operators.end();
3000 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003001 ++Oper)
John McCall6e9f8f62009-12-03 04:06:58 +00003002 AddMethodCandidate(*Oper, Args[0]->getType(),
3003 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003004 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003005 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003006}
3007
Douglas Gregora11693b2008-11-12 17:17:38 +00003008/// AddBuiltinCandidate - Add a candidate for a built-in
3009/// operator. ResultTy and ParamTys are the result and parameter types
3010/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003011/// arguments being passed to the candidate. IsAssignmentOperator
3012/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003013/// operator. NumContextualBoolArguments is the number of arguments
3014/// (at the beginning of the argument list) that will be contextually
3015/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003016void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003017 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003018 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003019 bool IsAssignmentOperator,
3020 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003021 // Overload resolution is always an unevaluated context.
3022 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3023
Douglas Gregora11693b2008-11-12 17:17:38 +00003024 // Add this candidate
3025 CandidateSet.push_back(OverloadCandidate());
3026 OverloadCandidate& Candidate = CandidateSet.back();
3027 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003028 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003029 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003030 Candidate.BuiltinTypes.ResultTy = ResultTy;
3031 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3032 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3033
3034 // Determine the implicit conversion sequences for each of the
3035 // arguments.
3036 Candidate.Viable = true;
3037 Candidate.Conversions.resize(NumArgs);
3038 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003039 // C++ [over.match.oper]p4:
3040 // For the built-in assignment operators, conversions of the
3041 // left operand are restricted as follows:
3042 // -- no temporaries are introduced to hold the left operand, and
3043 // -- no user-defined conversions are applied to the left
3044 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003045 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003046 //
3047 // We block these conversions by turning off user-defined
3048 // conversions, since that is the only way that initialization of
3049 // a reference to a non-class type can occur from something that
3050 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003051 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003052 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003053 "Contextual conversion to bool requires bool type");
3054 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3055 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003056 Candidate.Conversions[ArgIdx]
3057 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003058 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003059 /*ForceRValue=*/false,
3060 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003061 }
John McCall0d1da222010-01-12 00:44:57 +00003062 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003063 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003064 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003065 break;
3066 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003067 }
3068}
3069
3070/// BuiltinCandidateTypeSet - A set of types that will be used for the
3071/// candidate operator functions for built-in operators (C++
3072/// [over.built]). The types are separated into pointer types and
3073/// enumeration types.
3074class BuiltinCandidateTypeSet {
3075 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003076 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003077
3078 /// PointerTypes - The set of pointer types that will be used in the
3079 /// built-in candidates.
3080 TypeSet PointerTypes;
3081
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003082 /// MemberPointerTypes - The set of member pointer types that will be
3083 /// used in the built-in candidates.
3084 TypeSet MemberPointerTypes;
3085
Douglas Gregora11693b2008-11-12 17:17:38 +00003086 /// EnumerationTypes - The set of enumeration types that will be
3087 /// used in the built-in candidates.
3088 TypeSet EnumerationTypes;
3089
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003090 /// Sema - The semantic analysis instance where we are building the
3091 /// candidate type set.
3092 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003093
Douglas Gregora11693b2008-11-12 17:17:38 +00003094 /// Context - The AST context in which we will build the type sets.
3095 ASTContext &Context;
3096
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003097 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3098 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003099 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003100
3101public:
3102 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003103 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003104
Mike Stump11289f42009-09-09 15:08:12 +00003105 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003106 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003107
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003108 void AddTypesConvertedFrom(QualType Ty,
3109 SourceLocation Loc,
3110 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003111 bool AllowExplicitConversions,
3112 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003113
3114 /// pointer_begin - First pointer type found;
3115 iterator pointer_begin() { return PointerTypes.begin(); }
3116
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003117 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003118 iterator pointer_end() { return PointerTypes.end(); }
3119
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003120 /// member_pointer_begin - First member pointer type found;
3121 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3122
3123 /// member_pointer_end - Past the last member pointer type found;
3124 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3125
Douglas Gregora11693b2008-11-12 17:17:38 +00003126 /// enumeration_begin - First enumeration type found;
3127 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3128
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003129 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003130 iterator enumeration_end() { return EnumerationTypes.end(); }
3131};
3132
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003133/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003134/// the set of pointer types along with any more-qualified variants of
3135/// that type. For example, if @p Ty is "int const *", this routine
3136/// will add "int const *", "int const volatile *", "int const
3137/// restrict *", and "int const volatile restrict *" to the set of
3138/// pointer types. Returns true if the add of @p Ty itself succeeded,
3139/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003140///
3141/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003142bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003143BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3144 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003145
Douglas Gregora11693b2008-11-12 17:17:38 +00003146 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003147 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003148 return false;
3149
John McCall8ccfcb52009-09-24 19:53:00 +00003150 const PointerType *PointerTy = Ty->getAs<PointerType>();
3151 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003152
John McCall8ccfcb52009-09-24 19:53:00 +00003153 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003154 // Don't add qualified variants of arrays. For one, they're not allowed
3155 // (the qualifier would sink to the element type), and for another, the
3156 // only overload situation where it matters is subscript or pointer +- int,
3157 // and those shouldn't have qualifier variants anyway.
3158 if (PointeeTy->isArrayType())
3159 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003160 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003161 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003162 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003163 bool hasVolatile = VisibleQuals.hasVolatile();
3164 bool hasRestrict = VisibleQuals.hasRestrict();
3165
John McCall8ccfcb52009-09-24 19:53:00 +00003166 // Iterate through all strict supersets of BaseCVR.
3167 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3168 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003169 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3170 // in the types.
3171 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3172 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003173 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3174 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003175 }
3176
3177 return true;
3178}
3179
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003180/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3181/// to the set of pointer types along with any more-qualified variants of
3182/// that type. For example, if @p Ty is "int const *", this routine
3183/// will add "int const *", "int const volatile *", "int const
3184/// restrict *", and "int const volatile restrict *" to the set of
3185/// pointer types. Returns true if the add of @p Ty itself succeeded,
3186/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003187///
3188/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003189bool
3190BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3191 QualType Ty) {
3192 // Insert this type.
3193 if (!MemberPointerTypes.insert(Ty))
3194 return false;
3195
John McCall8ccfcb52009-09-24 19:53:00 +00003196 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3197 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003198
John McCall8ccfcb52009-09-24 19:53:00 +00003199 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003200 // Don't add qualified variants of arrays. For one, they're not allowed
3201 // (the qualifier would sink to the element type), and for another, the
3202 // only overload situation where it matters is subscript or pointer +- int,
3203 // and those shouldn't have qualifier variants anyway.
3204 if (PointeeTy->isArrayType())
3205 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003206 const Type *ClassTy = PointerTy->getClass();
3207
3208 // Iterate through all strict supersets of the pointee type's CVR
3209 // qualifiers.
3210 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3211 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3212 if ((CVR | BaseCVR) != CVR) continue;
3213
3214 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3215 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003216 }
3217
3218 return true;
3219}
3220
Douglas Gregora11693b2008-11-12 17:17:38 +00003221/// AddTypesConvertedFrom - Add each of the types to which the type @p
3222/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003223/// primarily interested in pointer types and enumeration types. We also
3224/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003225/// AllowUserConversions is true if we should look at the conversion
3226/// functions of a class type, and AllowExplicitConversions if we
3227/// should also include the explicit conversion functions of a class
3228/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003229void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003230BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003231 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003232 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003233 bool AllowExplicitConversions,
3234 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003235 // Only deal with canonical types.
3236 Ty = Context.getCanonicalType(Ty);
3237
3238 // Look through reference types; they aren't part of the type of an
3239 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003240 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003241 Ty = RefTy->getPointeeType();
3242
3243 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003244 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003245
Sebastian Redl65ae2002009-11-05 16:36:20 +00003246 // If we're dealing with an array type, decay to the pointer.
3247 if (Ty->isArrayType())
3248 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3249
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003250 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003251 QualType PointeeTy = PointerTy->getPointeeType();
3252
3253 // Insert our type, and its more-qualified variants, into the set
3254 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003255 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003256 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003257 } else if (Ty->isMemberPointerType()) {
3258 // Member pointers are far easier, since the pointee can't be converted.
3259 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3260 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003261 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003262 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003263 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003264 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003265 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003266 // No conversion functions in incomplete types.
3267 return;
3268 }
Mike Stump11289f42009-09-09 15:08:12 +00003269
Douglas Gregora11693b2008-11-12 17:17:38 +00003270 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalld14a8642009-11-21 08:51:07 +00003271 const UnresolvedSet *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003272 = ClassDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00003273 for (UnresolvedSet::iterator I = Conversions->begin(),
3274 E = Conversions->end(); I != E; ++I) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003275
Mike Stump11289f42009-09-09 15:08:12 +00003276 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003277 // about which builtin types we can convert to.
John McCalld14a8642009-11-21 08:51:07 +00003278 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor05155d82009-08-21 23:19:43 +00003279 continue;
3280
John McCalld14a8642009-11-21 08:51:07 +00003281 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003282 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003283 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003284 VisibleQuals);
3285 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003286 }
3287 }
3288 }
3289}
3290
Douglas Gregor84605ae2009-08-24 13:43:27 +00003291/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3292/// the volatile- and non-volatile-qualified assignment operators for the
3293/// given type to the candidate set.
3294static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3295 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003296 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003297 unsigned NumArgs,
3298 OverloadCandidateSet &CandidateSet) {
3299 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003300
Douglas Gregor84605ae2009-08-24 13:43:27 +00003301 // T& operator=(T&, T)
3302 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3303 ParamTypes[1] = T;
3304 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3305 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003306
Douglas Gregor84605ae2009-08-24 13:43:27 +00003307 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3308 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003309 ParamTypes[0]
3310 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003311 ParamTypes[1] = T;
3312 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003313 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003314 }
3315}
Mike Stump11289f42009-09-09 15:08:12 +00003316
Sebastian Redl1054fae2009-10-25 17:03:50 +00003317/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3318/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003319static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3320 Qualifiers VRQuals;
3321 const RecordType *TyRec;
3322 if (const MemberPointerType *RHSMPType =
3323 ArgExpr->getType()->getAs<MemberPointerType>())
3324 TyRec = cast<RecordType>(RHSMPType->getClass());
3325 else
3326 TyRec = ArgExpr->getType()->getAs<RecordType>();
3327 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003328 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003329 VRQuals.addVolatile();
3330 VRQuals.addRestrict();
3331 return VRQuals;
3332 }
3333
3334 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalld14a8642009-11-21 08:51:07 +00003335 const UnresolvedSet *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003336 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003337
John McCalld14a8642009-11-21 08:51:07 +00003338 for (UnresolvedSet::iterator I = Conversions->begin(),
3339 E = Conversions->end(); I != E; ++I) {
3340 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003341 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3342 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3343 CanTy = ResTypeRef->getPointeeType();
3344 // Need to go down the pointer/mempointer chain and add qualifiers
3345 // as see them.
3346 bool done = false;
3347 while (!done) {
3348 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3349 CanTy = ResTypePtr->getPointeeType();
3350 else if (const MemberPointerType *ResTypeMPtr =
3351 CanTy->getAs<MemberPointerType>())
3352 CanTy = ResTypeMPtr->getPointeeType();
3353 else
3354 done = true;
3355 if (CanTy.isVolatileQualified())
3356 VRQuals.addVolatile();
3357 if (CanTy.isRestrictQualified())
3358 VRQuals.addRestrict();
3359 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3360 return VRQuals;
3361 }
3362 }
3363 }
3364 return VRQuals;
3365}
3366
Douglas Gregord08452f2008-11-19 15:42:04 +00003367/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3368/// operator overloads to the candidate set (C++ [over.built]), based
3369/// on the operator @p Op and the arguments given. For example, if the
3370/// operator is a binary '+', this routine might add "int
3371/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003372void
Mike Stump11289f42009-09-09 15:08:12 +00003373Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003374 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003375 Expr **Args, unsigned NumArgs,
3376 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003377 // The set of "promoted arithmetic types", which are the arithmetic
3378 // types are that preserved by promotion (C++ [over.built]p2). Note
3379 // that the first few of these types are the promoted integral
3380 // types; these types need to be first.
3381 // FIXME: What about complex?
3382 const unsigned FirstIntegralType = 0;
3383 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003384 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003385 LastPromotedIntegralType = 13;
3386 const unsigned FirstPromotedArithmeticType = 7,
3387 LastPromotedArithmeticType = 16;
3388 const unsigned NumArithmeticTypes = 16;
3389 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003390 Context.BoolTy, Context.CharTy, Context.WCharTy,
3391// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003392 Context.SignedCharTy, Context.ShortTy,
3393 Context.UnsignedCharTy, Context.UnsignedShortTy,
3394 Context.IntTy, Context.LongTy, Context.LongLongTy,
3395 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3396 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3397 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003398 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3399 "Invalid first promoted integral type");
3400 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3401 == Context.UnsignedLongLongTy &&
3402 "Invalid last promoted integral type");
3403 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3404 "Invalid first promoted arithmetic type");
3405 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3406 == Context.LongDoubleTy &&
3407 "Invalid last promoted arithmetic type");
3408
Douglas Gregora11693b2008-11-12 17:17:38 +00003409 // Find all of the types that the arguments can convert to, but only
3410 // if the operator we're looking at has built-in operator candidates
3411 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003412 Qualifiers VisibleTypeConversionsQuals;
3413 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003414 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3415 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3416
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003417 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003418 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3419 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003420 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003421 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003422 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003423 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003424 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003425 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003426 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003427 true,
3428 (Op == OO_Exclaim ||
3429 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003430 Op == OO_PipePipe),
3431 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003432 }
3433
3434 bool isComparison = false;
3435 switch (Op) {
3436 case OO_None:
3437 case NUM_OVERLOADED_OPERATORS:
3438 assert(false && "Expected an overloaded operator");
3439 break;
3440
Douglas Gregord08452f2008-11-19 15:42:04 +00003441 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003442 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003443 goto UnaryStar;
3444 else
3445 goto BinaryStar;
3446 break;
3447
3448 case OO_Plus: // '+' is either unary or binary
3449 if (NumArgs == 1)
3450 goto UnaryPlus;
3451 else
3452 goto BinaryPlus;
3453 break;
3454
3455 case OO_Minus: // '-' is either unary or binary
3456 if (NumArgs == 1)
3457 goto UnaryMinus;
3458 else
3459 goto BinaryMinus;
3460 break;
3461
3462 case OO_Amp: // '&' is either unary or binary
3463 if (NumArgs == 1)
3464 goto UnaryAmp;
3465 else
3466 goto BinaryAmp;
3467
3468 case OO_PlusPlus:
3469 case OO_MinusMinus:
3470 // C++ [over.built]p3:
3471 //
3472 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3473 // is either volatile or empty, there exist candidate operator
3474 // functions of the form
3475 //
3476 // VQ T& operator++(VQ T&);
3477 // T operator++(VQ T&, int);
3478 //
3479 // C++ [over.built]p4:
3480 //
3481 // For every pair (T, VQ), where T is an arithmetic type other
3482 // than bool, and VQ is either volatile or empty, there exist
3483 // candidate operator functions of the form
3484 //
3485 // VQ T& operator--(VQ T&);
3486 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003487 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003488 Arith < NumArithmeticTypes; ++Arith) {
3489 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003490 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003491 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003492
3493 // Non-volatile version.
3494 if (NumArgs == 1)
3495 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3496 else
3497 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003498 // heuristic to reduce number of builtin candidates in the set.
3499 // Add volatile version only if there are conversions to a volatile type.
3500 if (VisibleTypeConversionsQuals.hasVolatile()) {
3501 // Volatile version
3502 ParamTypes[0]
3503 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3504 if (NumArgs == 1)
3505 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3506 else
3507 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3508 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003509 }
3510
3511 // C++ [over.built]p5:
3512 //
3513 // For every pair (T, VQ), where T is a cv-qualified or
3514 // cv-unqualified object type, and VQ is either volatile or
3515 // empty, there exist candidate operator functions of the form
3516 //
3517 // T*VQ& operator++(T*VQ&);
3518 // T*VQ& operator--(T*VQ&);
3519 // T* operator++(T*VQ&, int);
3520 // T* operator--(T*VQ&, int);
3521 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3522 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3523 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003524 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003525 continue;
3526
Mike Stump11289f42009-09-09 15:08:12 +00003527 QualType ParamTypes[2] = {
3528 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003529 };
Mike Stump11289f42009-09-09 15:08:12 +00003530
Douglas Gregord08452f2008-11-19 15:42:04 +00003531 // Without volatile
3532 if (NumArgs == 1)
3533 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3534 else
3535 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3536
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003537 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3538 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003539 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003540 ParamTypes[0]
3541 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003542 if (NumArgs == 1)
3543 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3544 else
3545 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3546 }
3547 }
3548 break;
3549
3550 UnaryStar:
3551 // C++ [over.built]p6:
3552 // For every cv-qualified or cv-unqualified object type T, there
3553 // exist candidate operator functions of the form
3554 //
3555 // T& operator*(T*);
3556 //
3557 // C++ [over.built]p7:
3558 // For every function type T, there exist candidate operator
3559 // functions of the form
3560 // T& operator*(T*);
3561 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3562 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3563 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003564 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003565 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003566 &ParamTy, Args, 1, CandidateSet);
3567 }
3568 break;
3569
3570 UnaryPlus:
3571 // C++ [over.built]p8:
3572 // For every type T, there exist candidate operator functions of
3573 // the form
3574 //
3575 // T* operator+(T*);
3576 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3577 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3578 QualType ParamTy = *Ptr;
3579 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3580 }
Mike Stump11289f42009-09-09 15:08:12 +00003581
Douglas Gregord08452f2008-11-19 15:42:04 +00003582 // Fall through
3583
3584 UnaryMinus:
3585 // C++ [over.built]p9:
3586 // For every promoted arithmetic type T, there exist candidate
3587 // operator functions of the form
3588 //
3589 // T operator+(T);
3590 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003591 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003592 Arith < LastPromotedArithmeticType; ++Arith) {
3593 QualType ArithTy = ArithmeticTypes[Arith];
3594 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3595 }
3596 break;
3597
3598 case OO_Tilde:
3599 // C++ [over.built]p10:
3600 // For every promoted integral type T, there exist candidate
3601 // operator functions of the form
3602 //
3603 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003604 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003605 Int < LastPromotedIntegralType; ++Int) {
3606 QualType IntTy = ArithmeticTypes[Int];
3607 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3608 }
3609 break;
3610
Douglas Gregora11693b2008-11-12 17:17:38 +00003611 case OO_New:
3612 case OO_Delete:
3613 case OO_Array_New:
3614 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003615 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003616 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003617 break;
3618
3619 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003620 UnaryAmp:
3621 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003622 // C++ [over.match.oper]p3:
3623 // -- For the operator ',', the unary operator '&', or the
3624 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003625 break;
3626
Douglas Gregor84605ae2009-08-24 13:43:27 +00003627 case OO_EqualEqual:
3628 case OO_ExclaimEqual:
3629 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003630 // For every pointer to member type T, there exist candidate operator
3631 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003632 //
3633 // bool operator==(T,T);
3634 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003635 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003636 MemPtr = CandidateTypes.member_pointer_begin(),
3637 MemPtrEnd = CandidateTypes.member_pointer_end();
3638 MemPtr != MemPtrEnd;
3639 ++MemPtr) {
3640 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3641 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3642 }
Mike Stump11289f42009-09-09 15:08:12 +00003643
Douglas Gregor84605ae2009-08-24 13:43:27 +00003644 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003645
Douglas Gregora11693b2008-11-12 17:17:38 +00003646 case OO_Less:
3647 case OO_Greater:
3648 case OO_LessEqual:
3649 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003650 // C++ [over.built]p15:
3651 //
3652 // For every pointer or enumeration type T, there exist
3653 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003654 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003655 // bool operator<(T, T);
3656 // bool operator>(T, T);
3657 // bool operator<=(T, T);
3658 // bool operator>=(T, T);
3659 // bool operator==(T, T);
3660 // bool operator!=(T, T);
3661 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3662 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3663 QualType ParamTypes[2] = { *Ptr, *Ptr };
3664 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3665 }
Mike Stump11289f42009-09-09 15:08:12 +00003666 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003667 = CandidateTypes.enumeration_begin();
3668 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3669 QualType ParamTypes[2] = { *Enum, *Enum };
3670 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3671 }
3672
3673 // Fall through.
3674 isComparison = true;
3675
Douglas Gregord08452f2008-11-19 15:42:04 +00003676 BinaryPlus:
3677 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003678 if (!isComparison) {
3679 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3680
3681 // C++ [over.built]p13:
3682 //
3683 // For every cv-qualified or cv-unqualified object type T
3684 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003685 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003686 // T* operator+(T*, ptrdiff_t);
3687 // T& operator[](T*, ptrdiff_t); [BELOW]
3688 // T* operator-(T*, ptrdiff_t);
3689 // T* operator+(ptrdiff_t, T*);
3690 // T& operator[](ptrdiff_t, T*); [BELOW]
3691 //
3692 // C++ [over.built]p14:
3693 //
3694 // For every T, where T is a pointer to object type, there
3695 // exist candidate operator functions of the form
3696 //
3697 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003698 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003699 = CandidateTypes.pointer_begin();
3700 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3701 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3702
3703 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3704 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3705
3706 if (Op == OO_Plus) {
3707 // T* operator+(ptrdiff_t, T*);
3708 ParamTypes[0] = ParamTypes[1];
3709 ParamTypes[1] = *Ptr;
3710 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3711 } else {
3712 // ptrdiff_t operator-(T, T);
3713 ParamTypes[1] = *Ptr;
3714 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3715 Args, 2, CandidateSet);
3716 }
3717 }
3718 }
3719 // Fall through
3720
Douglas Gregora11693b2008-11-12 17:17:38 +00003721 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003722 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003723 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003724 // C++ [over.built]p12:
3725 //
3726 // For every pair of promoted arithmetic types L and R, there
3727 // exist candidate operator functions of the form
3728 //
3729 // LR operator*(L, R);
3730 // LR operator/(L, R);
3731 // LR operator+(L, R);
3732 // LR operator-(L, R);
3733 // bool operator<(L, R);
3734 // bool operator>(L, R);
3735 // bool operator<=(L, R);
3736 // bool operator>=(L, R);
3737 // bool operator==(L, R);
3738 // bool operator!=(L, R);
3739 //
3740 // where LR is the result of the usual arithmetic conversions
3741 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003742 //
3743 // C++ [over.built]p24:
3744 //
3745 // For every pair of promoted arithmetic types L and R, there exist
3746 // candidate operator functions of the form
3747 //
3748 // LR operator?(bool, L, R);
3749 //
3750 // where LR is the result of the usual arithmetic conversions
3751 // between types L and R.
3752 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003753 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003754 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003755 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003756 Right < LastPromotedArithmeticType; ++Right) {
3757 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003758 QualType Result
3759 = isComparison
3760 ? Context.BoolTy
3761 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003762 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3763 }
3764 }
3765 break;
3766
3767 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003768 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003769 case OO_Caret:
3770 case OO_Pipe:
3771 case OO_LessLess:
3772 case OO_GreaterGreater:
3773 // C++ [over.built]p17:
3774 //
3775 // For every pair of promoted integral types L and R, there
3776 // exist candidate operator functions of the form
3777 //
3778 // LR operator%(L, R);
3779 // LR operator&(L, R);
3780 // LR operator^(L, R);
3781 // LR operator|(L, R);
3782 // L operator<<(L, R);
3783 // L operator>>(L, R);
3784 //
3785 // where LR is the result of the usual arithmetic conversions
3786 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003787 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003788 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003789 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003790 Right < LastPromotedIntegralType; ++Right) {
3791 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3792 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3793 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003794 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003795 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3796 }
3797 }
3798 break;
3799
3800 case OO_Equal:
3801 // C++ [over.built]p20:
3802 //
3803 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003804 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003805 // empty, there exist candidate operator functions of the form
3806 //
3807 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003808 for (BuiltinCandidateTypeSet::iterator
3809 Enum = CandidateTypes.enumeration_begin(),
3810 EnumEnd = CandidateTypes.enumeration_end();
3811 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003812 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003813 CandidateSet);
3814 for (BuiltinCandidateTypeSet::iterator
3815 MemPtr = CandidateTypes.member_pointer_begin(),
3816 MemPtrEnd = CandidateTypes.member_pointer_end();
3817 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003818 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003819 CandidateSet);
3820 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003821
3822 case OO_PlusEqual:
3823 case OO_MinusEqual:
3824 // C++ [over.built]p19:
3825 //
3826 // For every pair (T, VQ), where T is any type and VQ is either
3827 // volatile or empty, there exist candidate operator functions
3828 // of the form
3829 //
3830 // T*VQ& operator=(T*VQ&, T*);
3831 //
3832 // C++ [over.built]p21:
3833 //
3834 // For every pair (T, VQ), where T is a cv-qualified or
3835 // cv-unqualified object type and VQ is either volatile or
3836 // empty, there exist candidate operator functions of the form
3837 //
3838 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3839 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3840 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3841 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3842 QualType ParamTypes[2];
3843 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3844
3845 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003846 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003847 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3848 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003849
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003850 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3851 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003852 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003853 ParamTypes[0]
3854 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003855 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3856 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003857 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003858 }
3859 // Fall through.
3860
3861 case OO_StarEqual:
3862 case OO_SlashEqual:
3863 // C++ [over.built]p18:
3864 //
3865 // For every triple (L, VQ, R), where L is an arithmetic type,
3866 // VQ is either volatile or empty, and R is a promoted
3867 // arithmetic type, there exist candidate operator functions of
3868 // the form
3869 //
3870 // VQ L& operator=(VQ L&, R);
3871 // VQ L& operator*=(VQ L&, R);
3872 // VQ L& operator/=(VQ L&, R);
3873 // VQ L& operator+=(VQ L&, R);
3874 // VQ L& operator-=(VQ L&, R);
3875 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003876 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003877 Right < LastPromotedArithmeticType; ++Right) {
3878 QualType ParamTypes[2];
3879 ParamTypes[1] = ArithmeticTypes[Right];
3880
3881 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003882 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003883 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3884 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003885
3886 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003887 if (VisibleTypeConversionsQuals.hasVolatile()) {
3888 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3889 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3890 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3891 /*IsAssigmentOperator=*/Op == OO_Equal);
3892 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003893 }
3894 }
3895 break;
3896
3897 case OO_PercentEqual:
3898 case OO_LessLessEqual:
3899 case OO_GreaterGreaterEqual:
3900 case OO_AmpEqual:
3901 case OO_CaretEqual:
3902 case OO_PipeEqual:
3903 // C++ [over.built]p22:
3904 //
3905 // For every triple (L, VQ, R), where L is an integral type, VQ
3906 // is either volatile or empty, and R is a promoted integral
3907 // type, there exist candidate operator functions of the form
3908 //
3909 // VQ L& operator%=(VQ L&, R);
3910 // VQ L& operator<<=(VQ L&, R);
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 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003916 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003917 Right < LastPromotedIntegralType; ++Right) {
3918 QualType ParamTypes[2];
3919 ParamTypes[1] = ArithmeticTypes[Right];
3920
3921 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003922 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003923 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00003924 if (VisibleTypeConversionsQuals.hasVolatile()) {
3925 // Add this built-in operator as a candidate (VQ is 'volatile').
3926 ParamTypes[0] = ArithmeticTypes[Left];
3927 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3928 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3929 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3930 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003931 }
3932 }
3933 break;
3934
Douglas Gregord08452f2008-11-19 15:42:04 +00003935 case OO_Exclaim: {
3936 // C++ [over.operator]p23:
3937 //
3938 // There also exist candidate operator functions of the form
3939 //
Mike Stump11289f42009-09-09 15:08:12 +00003940 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003941 // bool operator&&(bool, bool); [BELOW]
3942 // bool operator||(bool, bool); [BELOW]
3943 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003944 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3945 /*IsAssignmentOperator=*/false,
3946 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003947 break;
3948 }
3949
Douglas Gregora11693b2008-11-12 17:17:38 +00003950 case OO_AmpAmp:
3951 case OO_PipePipe: {
3952 // C++ [over.operator]p23:
3953 //
3954 // There also exist candidate operator functions of the form
3955 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003956 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003957 // bool operator&&(bool, bool);
3958 // bool operator||(bool, bool);
3959 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003960 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3961 /*IsAssignmentOperator=*/false,
3962 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003963 break;
3964 }
3965
3966 case OO_Subscript:
3967 // C++ [over.built]p13:
3968 //
3969 // For every cv-qualified or cv-unqualified object type T there
3970 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003971 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003972 // T* operator+(T*, ptrdiff_t); [ABOVE]
3973 // T& operator[](T*, ptrdiff_t);
3974 // T* operator-(T*, ptrdiff_t); [ABOVE]
3975 // T* operator+(ptrdiff_t, T*); [ABOVE]
3976 // T& operator[](ptrdiff_t, T*);
3977 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3978 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3979 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003980 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003981 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003982
3983 // T& operator[](T*, ptrdiff_t)
3984 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3985
3986 // T& operator[](ptrdiff_t, T*);
3987 ParamTypes[0] = ParamTypes[1];
3988 ParamTypes[1] = *Ptr;
3989 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3990 }
3991 break;
3992
3993 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003994 // C++ [over.built]p11:
3995 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3996 // C1 is the same type as C2 or is a derived class of C2, T is an object
3997 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3998 // there exist candidate operator functions of the form
3999 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4000 // where CV12 is the union of CV1 and CV2.
4001 {
4002 for (BuiltinCandidateTypeSet::iterator Ptr =
4003 CandidateTypes.pointer_begin();
4004 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4005 QualType C1Ty = (*Ptr);
4006 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004007 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004008 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004009 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004010 if (!isa<RecordType>(C1))
4011 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004012 // heuristic to reduce number of builtin candidates in the set.
4013 // Add volatile/restrict version only if there are conversions to a
4014 // volatile/restrict type.
4015 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4016 continue;
4017 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4018 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004019 }
4020 for (BuiltinCandidateTypeSet::iterator
4021 MemPtr = CandidateTypes.member_pointer_begin(),
4022 MemPtrEnd = CandidateTypes.member_pointer_end();
4023 MemPtr != MemPtrEnd; ++MemPtr) {
4024 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4025 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004026 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004027 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4028 break;
4029 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4030 // build CV12 T&
4031 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004032 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4033 T.isVolatileQualified())
4034 continue;
4035 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4036 T.isRestrictQualified())
4037 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004038 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004039 QualType ResultTy = Context.getLValueReferenceType(T);
4040 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4041 }
4042 }
4043 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004044 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004045
4046 case OO_Conditional:
4047 // Note that we don't consider the first argument, since it has been
4048 // contextually converted to bool long ago. The candidates below are
4049 // therefore added as binary.
4050 //
4051 // C++ [over.built]p24:
4052 // For every type T, where T is a pointer or pointer-to-member type,
4053 // there exist candidate operator functions of the form
4054 //
4055 // T operator?(bool, T, T);
4056 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004057 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4058 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4059 QualType ParamTypes[2] = { *Ptr, *Ptr };
4060 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4061 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004062 for (BuiltinCandidateTypeSet::iterator Ptr =
4063 CandidateTypes.member_pointer_begin(),
4064 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4065 QualType ParamTypes[2] = { *Ptr, *Ptr };
4066 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4067 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004068 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004069 }
4070}
4071
Douglas Gregore254f902009-02-04 00:32:51 +00004072/// \brief Add function candidates found via argument-dependent lookup
4073/// to the set of overloading candidates.
4074///
4075/// This routine performs argument-dependent name lookup based on the
4076/// given function name (which may also be an operator name) and adds
4077/// all of the overload candidates found by ADL to the overload
4078/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004079void
Douglas Gregore254f902009-02-04 00:32:51 +00004080Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
4081 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004082 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004083 OverloadCandidateSet& CandidateSet,
4084 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004085 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00004086
Douglas Gregorcabea402009-09-22 15:41:20 +00004087 // FIXME: Should we be trafficking in canonical function decls throughout?
4088
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004089 // Record all of the function candidates that we've already
4090 // added to the overload set, so that we don't add those same
4091 // candidates a second time.
4092 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4093 CandEnd = CandidateSet.end();
4094 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004095 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004096 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004097 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4098 Functions.insert(FunTmpl);
4099 }
Douglas Gregore254f902009-02-04 00:32:51 +00004100
Douglas Gregorcabea402009-09-22 15:41:20 +00004101 // FIXME: Pass in the explicit template arguments?
Sebastian Redlc057f422009-10-23 19:23:15 +00004102 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00004103
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004104 // Erase all of the candidates we already knew about.
4105 // FIXME: This is suboptimal. Is there a better way?
4106 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4107 CandEnd = CandidateSet.end();
4108 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004109 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004110 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004111 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4112 Functions.erase(FunTmpl);
4113 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004114
4115 // For each of the ADL candidates we found, add it to the overload
4116 // set.
4117 for (FunctionSet::iterator Func = Functions.begin(),
4118 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00004119 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00004120 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
John McCall6b51f282009-11-23 01:53:49 +00004121 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004122 continue;
4123
4124 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
4125 false, false, PartialOverloading);
4126 } else
Mike Stump11289f42009-09-09 15:08:12 +00004127 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00004128 ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004129 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004130 }
Douglas Gregore254f902009-02-04 00:32:51 +00004131}
4132
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004133/// isBetterOverloadCandidate - Determines whether the first overload
4134/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004135bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004136Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00004137 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004138 // Define viable functions to be better candidates than non-viable
4139 // functions.
4140 if (!Cand2.Viable)
4141 return Cand1.Viable;
4142 else if (!Cand1.Viable)
4143 return false;
4144
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004145 // C++ [over.match.best]p1:
4146 //
4147 // -- if F is a static member function, ICS1(F) is defined such
4148 // that ICS1(F) is neither better nor worse than ICS1(G) for
4149 // any function G, and, symmetrically, ICS1(G) is neither
4150 // better nor worse than ICS1(F).
4151 unsigned StartArg = 0;
4152 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4153 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004154
Douglas Gregord3cb3562009-07-07 23:38:56 +00004155 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004156 // A viable function F1 is defined to be a better function than another
4157 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004158 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004159 unsigned NumArgs = Cand1.Conversions.size();
4160 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4161 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004162 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004163 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4164 Cand2.Conversions[ArgIdx])) {
4165 case ImplicitConversionSequence::Better:
4166 // Cand1 has a better conversion sequence.
4167 HasBetterConversion = true;
4168 break;
4169
4170 case ImplicitConversionSequence::Worse:
4171 // Cand1 can't be better than Cand2.
4172 return false;
4173
4174 case ImplicitConversionSequence::Indistinguishable:
4175 // Do nothing.
4176 break;
4177 }
4178 }
4179
Mike Stump11289f42009-09-09 15:08:12 +00004180 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004181 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004182 if (HasBetterConversion)
4183 return true;
4184
Mike Stump11289f42009-09-09 15:08:12 +00004185 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004186 // specialization, or, if not that,
4187 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4188 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4189 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004190
4191 // -- F1 and F2 are function template specializations, and the function
4192 // template for F1 is more specialized than the template for F2
4193 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004194 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004195 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4196 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004197 if (FunctionTemplateDecl *BetterTemplate
4198 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4199 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00004200 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4201 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004202 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004203
Douglas Gregora1f013e2008-11-07 22:36:19 +00004204 // -- the context is an initialization by user-defined conversion
4205 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4206 // from the return type of F1 to the destination type (i.e.,
4207 // the type of the entity being initialized) is a better
4208 // conversion sequence than the standard conversion sequence
4209 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004210 if (Cand1.Function && Cand2.Function &&
4211 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004212 isa<CXXConversionDecl>(Cand2.Function)) {
4213 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4214 Cand2.FinalConversion)) {
4215 case ImplicitConversionSequence::Better:
4216 // Cand1 has a better conversion sequence.
4217 return true;
4218
4219 case ImplicitConversionSequence::Worse:
4220 // Cand1 can't be better than Cand2.
4221 return false;
4222
4223 case ImplicitConversionSequence::Indistinguishable:
4224 // Do nothing
4225 break;
4226 }
4227 }
4228
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004229 return false;
4230}
4231
Mike Stump11289f42009-09-09 15:08:12 +00004232/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004233/// within an overload candidate set.
4234///
4235/// \param CandidateSet the set of candidate functions.
4236///
4237/// \param Loc the location of the function name (or operator symbol) for
4238/// which overload resolution occurs.
4239///
Mike Stump11289f42009-09-09 15:08:12 +00004240/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004241/// function, Best points to the candidate function found.
4242///
4243/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004244OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4245 SourceLocation Loc,
4246 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004247 // Find the best viable function.
4248 Best = CandidateSet.end();
4249 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4250 Cand != CandidateSet.end(); ++Cand) {
4251 if (Cand->Viable) {
4252 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4253 Best = Cand;
4254 }
4255 }
4256
4257 // If we didn't find any viable functions, abort.
4258 if (Best == CandidateSet.end())
4259 return OR_No_Viable_Function;
4260
4261 // Make sure that this function is better than every other viable
4262 // function. If not, we have an ambiguity.
4263 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4264 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004265 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004266 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00004267 !isBetterOverloadCandidate(*Best, *Cand)) {
4268 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004269 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004270 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004271 }
Mike Stump11289f42009-09-09 15:08:12 +00004272
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004273 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004274 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004275 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004276 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004277 return OR_Deleted;
4278
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004279 // C++ [basic.def.odr]p2:
4280 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004281 // when referred to from a potentially-evaluated expression. [Note: this
4282 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004283 // (clause 13), user-defined conversions (12.3.2), allocation function for
4284 // placement new (5.3.4), as well as non-default initialization (8.5).
4285 if (Best->Function)
4286 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004287 return OR_Success;
4288}
4289
John McCall53262c92010-01-12 02:15:36 +00004290namespace {
4291
4292enum OverloadCandidateKind {
4293 oc_function,
4294 oc_method,
4295 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004296 oc_function_template,
4297 oc_method_template,
4298 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00004299 oc_implicit_default_constructor,
4300 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004301 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00004302};
4303
John McCalle1ac8d12010-01-13 00:25:19 +00004304OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4305 FunctionDecl *Fn,
4306 std::string &Description) {
4307 bool isTemplate = false;
4308
4309 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4310 isTemplate = true;
4311 Description = S.getTemplateArgumentBindingsText(
4312 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4313 }
John McCallfd0b2f82010-01-06 09:43:14 +00004314
4315 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004316 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004317 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004318
John McCall53262c92010-01-12 02:15:36 +00004319 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4320 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004321 }
4322
4323 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4324 // This actually gets spelled 'candidate function' for now, but
4325 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004326 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004327 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004328
4329 assert(Meth->isCopyAssignment()
4330 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004331 return oc_implicit_copy_assignment;
4332 }
4333
John McCalle1ac8d12010-01-13 00:25:19 +00004334 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00004335}
4336
4337} // end anonymous namespace
4338
4339// Notes the location of an overload candidate.
4340void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00004341 std::string FnDesc;
4342 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4343 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4344 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00004345}
4346
John McCall0d1da222010-01-12 00:44:57 +00004347/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4348/// "lead" diagnostic; it will be given two arguments, the source and
4349/// target types of the conversion.
4350void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4351 SourceLocation CaretLoc,
4352 const PartialDiagnostic &PDiag) {
4353 Diag(CaretLoc, PDiag)
4354 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4355 for (AmbiguousConversionSequence::const_iterator
4356 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4357 NoteOverloadCandidate(*I);
4358 }
John McCall12f97bc2010-01-08 04:41:39 +00004359}
4360
John McCall0d1da222010-01-12 00:44:57 +00004361namespace {
4362
John McCall6a61b522010-01-13 09:16:55 +00004363void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4364 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4365 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00004366 assert(Cand->Function && "for now, candidate must be a function");
4367 FunctionDecl *Fn = Cand->Function;
4368
4369 // There's a conversion slot for the object argument if this is a
4370 // non-constructor method. Note that 'I' corresponds the
4371 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00004372 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00004373 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00004374 if (I == 0)
4375 isObjectArgument = true;
4376 else
4377 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00004378 }
4379
John McCalle1ac8d12010-01-13 00:25:19 +00004380 std::string FnDesc;
4381 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4382
John McCall6a61b522010-01-13 09:16:55 +00004383 Expr *FromExpr = Conv.Bad.FromExpr;
4384 QualType FromTy = Conv.Bad.getFromType();
4385 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00004386
4387 // TODO: specialize based on the kind of mismatch
4388 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4389 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00004390 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4391 << FromTy << ToTy << I+1;
4392}
4393
4394void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4395 unsigned NumFormalArgs) {
4396 // TODO: treat calls to a missing default constructor as a special case
4397
4398 FunctionDecl *Fn = Cand->Function;
4399 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4400
4401 unsigned MinParams = Fn->getMinRequiredArguments();
4402
4403 // at least / at most / exactly
4404 unsigned mode, modeCount;
4405 if (NumFormalArgs < MinParams) {
4406 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4407 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4408 mode = 0; // "at least"
4409 else
4410 mode = 2; // "exactly"
4411 modeCount = MinParams;
4412 } else {
4413 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4414 if (MinParams != FnTy->getNumArgs())
4415 mode = 1; // "at most"
4416 else
4417 mode = 2; // "exactly"
4418 modeCount = FnTy->getNumArgs();
4419 }
4420
4421 std::string Description;
4422 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4423
4424 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4425 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00004426}
4427
4428void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4429 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00004430 FunctionDecl *Fn = Cand->Function;
4431
John McCall12f97bc2010-01-08 04:41:39 +00004432 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00004433 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00004434 std::string FnDesc;
4435 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00004436
4437 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00004438 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00004439 return;
John McCall12f97bc2010-01-08 04:41:39 +00004440 }
4441
John McCalle1ac8d12010-01-13 00:25:19 +00004442 // We don't really have anything else to say about viable candidates.
4443 if (Cand->Viable) {
4444 S.NoteOverloadCandidate(Fn);
4445 return;
4446 }
John McCall0d1da222010-01-12 00:44:57 +00004447
John McCall6a61b522010-01-13 09:16:55 +00004448 switch (Cand->FailureKind) {
4449 case ovl_fail_too_many_arguments:
4450 case ovl_fail_too_few_arguments:
4451 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00004452
John McCall6a61b522010-01-13 09:16:55 +00004453 case ovl_fail_bad_deduction:
4454 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004455
John McCall6a61b522010-01-13 09:16:55 +00004456 case ovl_fail_bad_conversion:
4457 for (unsigned I = 0, N = Cand->Conversions.size(); I != N; ++I)
4458 if (Cand->Conversions[I].isBad())
4459 return DiagnoseBadConversion(S, Cand, I);
4460
4461 // FIXME: this currently happens when we're called from SemaInit
4462 // when user-conversion overload fails. Figure out how to handle
4463 // those conditions and diagnose them well.
4464 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00004465 }
John McCalld3224162010-01-08 00:58:21 +00004466}
4467
4468void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4469 // Desugar the type of the surrogate down to a function type,
4470 // retaining as many typedefs as possible while still showing
4471 // the function type (and, therefore, its parameter types).
4472 QualType FnType = Cand->Surrogate->getConversionType();
4473 bool isLValueReference = false;
4474 bool isRValueReference = false;
4475 bool isPointer = false;
4476 if (const LValueReferenceType *FnTypeRef =
4477 FnType->getAs<LValueReferenceType>()) {
4478 FnType = FnTypeRef->getPointeeType();
4479 isLValueReference = true;
4480 } else if (const RValueReferenceType *FnTypeRef =
4481 FnType->getAs<RValueReferenceType>()) {
4482 FnType = FnTypeRef->getPointeeType();
4483 isRValueReference = true;
4484 }
4485 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4486 FnType = FnTypePtr->getPointeeType();
4487 isPointer = true;
4488 }
4489 // Desugar down to a function type.
4490 FnType = QualType(FnType->getAs<FunctionType>(), 0);
4491 // Reconstruct the pointer/reference as appropriate.
4492 if (isPointer) FnType = S.Context.getPointerType(FnType);
4493 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
4494 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
4495
4496 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
4497 << FnType;
4498}
4499
4500void NoteBuiltinOperatorCandidate(Sema &S,
4501 const char *Opc,
4502 SourceLocation OpLoc,
4503 OverloadCandidate *Cand) {
4504 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
4505 std::string TypeStr("operator");
4506 TypeStr += Opc;
4507 TypeStr += "(";
4508 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4509 if (Cand->Conversions.size() == 1) {
4510 TypeStr += ")";
4511 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
4512 } else {
4513 TypeStr += ", ";
4514 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4515 TypeStr += ")";
4516 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
4517 }
4518}
4519
4520void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
4521 OverloadCandidate *Cand) {
4522 unsigned NoOperands = Cand->Conversions.size();
4523 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4524 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00004525 if (ICS.isBad()) break; // all meaningless after first invalid
4526 if (!ICS.isAmbiguous()) continue;
4527
4528 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
4529 PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00004530 }
4531}
4532
John McCallad2587a2010-01-12 00:48:53 +00004533struct CompareOverloadCandidatesForDisplay {
4534 Sema &S;
4535 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00004536
4537 bool operator()(const OverloadCandidate *L,
4538 const OverloadCandidate *R) {
4539 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00004540 if (L->Viable) {
4541 if (!R->Viable) return true;
4542
4543 // TODO: introduce a tri-valued comparison for overload
4544 // candidates. Would be more worthwhile if we had a sort
4545 // that could exploit it.
4546 if (S.isBetterOverloadCandidate(*L, *R)) return true;
4547 if (S.isBetterOverloadCandidate(*R, *L)) return false;
4548 } else if (R->Viable)
4549 return false;
John McCall12f97bc2010-01-08 04:41:39 +00004550
4551 // Put declared functions first.
4552 if (L->Function) {
4553 if (!R->Function) return true;
John McCallad2587a2010-01-12 00:48:53 +00004554 return S.SourceMgr.isBeforeInTranslationUnit(L->Function->getLocation(),
4555 R->Function->getLocation());
John McCall12f97bc2010-01-08 04:41:39 +00004556 } else if (R->Function) return false;
4557
4558 // Then surrogates.
4559 if (L->IsSurrogate) {
4560 if (!R->IsSurrogate) return true;
John McCallad2587a2010-01-12 00:48:53 +00004561 return S.SourceMgr.isBeforeInTranslationUnit(L->Surrogate->getLocation(),
4562 R->Surrogate->getLocation());
John McCall12f97bc2010-01-08 04:41:39 +00004563 } else if (R->IsSurrogate) return false;
4564
4565 // And builtins just come in a jumble.
4566 return false;
4567 }
4568};
4569
John McCalld3224162010-01-08 00:58:21 +00004570} // end anonymous namespace
4571
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004572/// PrintOverloadCandidates - When overload resolution fails, prints
4573/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00004574/// set.
Mike Stump11289f42009-09-09 15:08:12 +00004575void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004576Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00004577 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00004578 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004579 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004580 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00004581 // Sort the candidates by viability and position. Sorting directly would
4582 // be prohibitive, so we make a set of pointers and sort those.
4583 llvm::SmallVector<OverloadCandidate*, 32> Cands;
4584 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
4585 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4586 LastCand = CandidateSet.end();
4587 Cand != LastCand; ++Cand)
4588 if (Cand->Viable || OCD == OCD_AllCandidates)
4589 Cands.push_back(Cand);
John McCallad2587a2010-01-12 00:48:53 +00004590 std::sort(Cands.begin(), Cands.end(),
4591 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00004592
John McCall0d1da222010-01-12 00:44:57 +00004593 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00004594
John McCall12f97bc2010-01-08 04:41:39 +00004595 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
4596 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
4597 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004598
John McCalld3224162010-01-08 00:58:21 +00004599 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00004600 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00004601 else if (Cand->IsSurrogate)
4602 NoteSurrogateCandidate(*this, Cand);
4603
4604 // This a builtin candidate. We do not, in general, want to list
4605 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00004606 else if (Cand->Viable) {
4607 // Generally we only see ambiguities including viable builtin
4608 // operators if overload resolution got screwed up by an
4609 // ambiguous user-defined conversion.
4610 //
4611 // FIXME: It's quite possible for different conversions to see
4612 // different ambiguities, though.
4613 if (!ReportedAmbiguousConversions) {
4614 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
4615 ReportedAmbiguousConversions = true;
4616 }
John McCalld3224162010-01-08 00:58:21 +00004617
John McCall0d1da222010-01-12 00:44:57 +00004618 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00004619 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00004620 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004621 }
4622}
4623
Douglas Gregorcd695e52008-11-10 20:40:00 +00004624/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4625/// an overloaded function (C++ [over.over]), where @p From is an
4626/// expression with overloaded function type and @p ToType is the type
4627/// we're trying to resolve to. For example:
4628///
4629/// @code
4630/// int f(double);
4631/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004632///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004633/// int (*pfd)(double) = f; // selects f(double)
4634/// @endcode
4635///
4636/// This routine returns the resulting FunctionDecl if it could be
4637/// resolved, and NULL otherwise. When @p Complain is true, this
4638/// routine will emit diagnostics if there is an error.
4639FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004640Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004641 bool Complain) {
4642 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004643 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004644 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004645 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004646 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004647 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004648 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004649 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004650 FunctionType = MemTypePtr->getPointeeType();
4651 IsMember = true;
4652 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004653
4654 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00004655 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00004656 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004657 return 0;
4658
4659 // Find the actual overloaded function declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004660
Douglas Gregorcd695e52008-11-10 20:40:00 +00004661 // C++ [over.over]p1:
4662 // [...] [Note: any redundant set of parentheses surrounding the
4663 // overloaded function name is ignored (5.1). ]
4664 Expr *OvlExpr = From->IgnoreParens();
4665
4666 // C++ [over.over]p1:
4667 // [...] The overloaded function name can be preceded by the &
4668 // operator.
4669 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4670 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4671 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4672 }
4673
Anders Carlssonb68b0282009-10-20 22:53:47 +00004674 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004675 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCalld14a8642009-11-21 08:51:07 +00004676
4677 llvm::SmallVector<NamedDecl*,8> Fns;
Anders Carlssonb68b0282009-10-20 22:53:47 +00004678
John McCall10eae182009-11-30 22:42:35 +00004679 // Look into the overloaded expression.
John McCalle66edc12009-11-24 19:00:30 +00004680 if (UnresolvedLookupExpr *UL
John McCalld14a8642009-11-21 08:51:07 +00004681 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4682 Fns.append(UL->decls_begin(), UL->decls_end());
John McCalle66edc12009-11-24 19:00:30 +00004683 if (UL->hasExplicitTemplateArgs()) {
4684 HasExplicitTemplateArgs = true;
4685 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4686 }
John McCall10eae182009-11-30 22:42:35 +00004687 } else if (UnresolvedMemberExpr *ME
4688 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4689 Fns.append(ME->decls_begin(), ME->decls_end());
4690 if (ME->hasExplicitTemplateArgs()) {
4691 HasExplicitTemplateArgs = true;
John McCall6b51f282009-11-23 01:53:49 +00004692 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004693 }
Douglas Gregor9b146582009-07-08 20:55:45 +00004694 }
Mike Stump11289f42009-09-09 15:08:12 +00004695
John McCalld14a8642009-11-21 08:51:07 +00004696 // If we didn't actually find anything, we're done.
4697 if (Fns.empty())
4698 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004699
Douglas Gregorcd695e52008-11-10 20:40:00 +00004700 // Look through all of the overloaded functions, searching for one
4701 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004702 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004703 bool FoundNonTemplateFunction = false;
John McCalld14a8642009-11-21 08:51:07 +00004704 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4705 E = Fns.end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004706 // Look through any using declarations to find the underlying function.
4707 NamedDecl *Fn = (*I)->getUnderlyingDecl();
4708
Douglas Gregorcd695e52008-11-10 20:40:00 +00004709 // C++ [over.over]p3:
4710 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00004711 // targets of type "pointer-to-function" or "reference-to-function."
4712 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004713 // type "pointer-to-member-function."
4714 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004715
Mike Stump11289f42009-09-09 15:08:12 +00004716 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004717 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00004718 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004719 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004720 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004721 // static when converting to member pointer.
4722 if (Method->isStatic() == IsMember)
4723 continue;
4724 } else if (IsMember)
4725 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004726
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004727 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004728 // If the name is a function template, template argument deduction is
4729 // done (14.8.2.2), and if the argument deduction succeeds, the
4730 // resulting template argument list is used to generate a single
4731 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004732 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004733 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00004734 FunctionDecl *Specialization = 0;
4735 TemplateDeductionInfo Info(Context);
4736 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004737 = DeduceTemplateArguments(FunctionTemplate,
4738 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
Douglas Gregor9b146582009-07-08 20:55:45 +00004739 FunctionType, Specialization, Info)) {
4740 // FIXME: make a note of the failed deduction for diagnostics.
4741 (void)Result;
4742 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004743 // FIXME: If the match isn't exact, shouldn't we just drop this as
4744 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00004745 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004746 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004747 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004748 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004749 }
John McCalld14a8642009-11-21 08:51:07 +00004750
4751 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00004752 }
Mike Stump11289f42009-09-09 15:08:12 +00004753
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004754 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004755 // Skip non-static functions when converting to pointer, and static
4756 // when converting to member pointer.
4757 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004758 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00004759
4760 // If we have explicit template arguments, skip non-templates.
4761 if (HasExplicitTemplateArgs)
4762 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004763 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004764 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004765
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00004766 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00004767 QualType ResultTy;
4768 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
4769 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
4770 ResultTy)) {
John McCalld14a8642009-11-21 08:51:07 +00004771 Matches.insert(cast<FunctionDecl>(FunDecl->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004772 FoundNonTemplateFunction = true;
4773 }
Mike Stump11289f42009-09-09 15:08:12 +00004774 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004775 }
4776
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004777 // If there were 0 or 1 matches, we're done.
4778 if (Matches.empty())
4779 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004780 else if (Matches.size() == 1) {
4781 FunctionDecl *Result = *Matches.begin();
4782 MarkDeclarationReferenced(From->getLocStart(), Result);
4783 return Result;
4784 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004785
4786 // C++ [over.over]p4:
4787 // If more than one function is selected, [...]
Douglas Gregor05155d82009-08-21 23:19:43 +00004788 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorfae1d712009-09-26 03:56:17 +00004789 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004790 // [...] and any given function template specialization F1 is
4791 // eliminated if the set contains a second function template
4792 // specialization whose function template is more specialized
4793 // than the function template of F1 according to the partial
4794 // ordering rules of 14.5.5.2.
4795
4796 // The algorithm specified above is quadratic. We instead use a
4797 // two-pass algorithm (similar to the one used to identify the
4798 // best viable function in an overload set) that identifies the
4799 // best function template (if it exists).
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004800 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregorfae1d712009-09-26 03:56:17 +00004801 Matches.end());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004802 FunctionDecl *Result =
4803 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4804 TPOC_Other, From->getLocStart(),
4805 PDiag(),
4806 PDiag(diag::err_addr_ovl_ambiguous)
4807 << TemplateMatches[0]->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00004808 PDiag(diag::note_ovl_candidate)
4809 << (unsigned) oc_function_template);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004810 MarkDeclarationReferenced(From->getLocStart(), Result);
4811 return Result;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004812 }
Mike Stump11289f42009-09-09 15:08:12 +00004813
Douglas Gregorfae1d712009-09-26 03:56:17 +00004814 // [...] any function template specializations in the set are
4815 // eliminated if the set also contains a non-template function, [...]
4816 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4817 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4818 if ((*M)->getPrimaryTemplate() == 0)
4819 RemainingMatches.push_back(*M);
4820
Mike Stump11289f42009-09-09 15:08:12 +00004821 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004822 // selected function.
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004823 if (RemainingMatches.size() == 1) {
4824 FunctionDecl *Result = RemainingMatches.front();
4825 MarkDeclarationReferenced(From->getLocStart(), Result);
4826 return Result;
4827 }
Mike Stump11289f42009-09-09 15:08:12 +00004828
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004829 // FIXME: We should probably return the same thing that BestViableFunction
4830 // returns (even if we issue the diagnostics here).
4831 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4832 << RemainingMatches[0]->getDeclName();
4833 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
John McCallfd0b2f82010-01-06 09:43:14 +00004834 NoteOverloadCandidate(RemainingMatches[I]);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004835 return 0;
4836}
4837
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004838/// \brief Given an expression that refers to an overloaded function, try to
4839/// resolve that overloaded function expression down to a single function.
4840///
4841/// This routine can only resolve template-ids that refer to a single function
4842/// template, where that template-id refers to a single template whose template
4843/// arguments are either provided by the template-id or have defaults,
4844/// as described in C++0x [temp.arg.explicit]p3.
4845FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
4846 // C++ [over.over]p1:
4847 // [...] [Note: any redundant set of parentheses surrounding the
4848 // overloaded function name is ignored (5.1). ]
4849 Expr *OvlExpr = From->IgnoreParens();
4850
4851 // C++ [over.over]p1:
4852 // [...] The overloaded function name can be preceded by the &
4853 // operator.
4854 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4855 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4856 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4857 }
4858
4859 bool HasExplicitTemplateArgs = false;
4860 TemplateArgumentListInfo ExplicitTemplateArgs;
4861
4862 llvm::SmallVector<NamedDecl*,8> Fns;
4863
4864 // Look into the overloaded expression.
4865 if (UnresolvedLookupExpr *UL
4866 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4867 Fns.append(UL->decls_begin(), UL->decls_end());
4868 if (UL->hasExplicitTemplateArgs()) {
4869 HasExplicitTemplateArgs = true;
4870 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4871 }
4872 } else if (UnresolvedMemberExpr *ME
4873 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4874 Fns.append(ME->decls_begin(), ME->decls_end());
4875 if (ME->hasExplicitTemplateArgs()) {
4876 HasExplicitTemplateArgs = true;
4877 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4878 }
4879 }
4880
4881 // If we didn't actually find any template-ids, we're done.
4882 if (Fns.empty() || !HasExplicitTemplateArgs)
4883 return 0;
4884
4885 // Look through all of the overloaded functions, searching for one
4886 // whose type matches exactly.
4887 FunctionDecl *Matched = 0;
4888 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4889 E = Fns.end(); I != E; ++I) {
4890 // C++0x [temp.arg.explicit]p3:
4891 // [...] In contexts where deduction is done and fails, or in contexts
4892 // where deduction is not done, if a template argument list is
4893 // specified and it, along with any default template arguments,
4894 // identifies a single function template specialization, then the
4895 // template-id is an lvalue for the function template specialization.
4896 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
4897
4898 // C++ [over.over]p2:
4899 // If the name is a function template, template argument deduction is
4900 // done (14.8.2.2), and if the argument deduction succeeds, the
4901 // resulting template argument list is used to generate a single
4902 // function template specialization, which is added to the set of
4903 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004904 FunctionDecl *Specialization = 0;
4905 TemplateDeductionInfo Info(Context);
4906 if (TemplateDeductionResult Result
4907 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
4908 Specialization, Info)) {
4909 // FIXME: make a note of the failed deduction for diagnostics.
4910 (void)Result;
4911 continue;
4912 }
4913
4914 // Multiple matches; we can't resolve to a single declaration.
4915 if (Matched)
4916 return 0;
4917
4918 Matched = Specialization;
4919 }
4920
4921 return Matched;
4922}
4923
Douglas Gregorcabea402009-09-22 15:41:20 +00004924/// \brief Add a single candidate to the overload set.
4925static void AddOverloadedCallCandidate(Sema &S,
John McCalld14a8642009-11-21 08:51:07 +00004926 NamedDecl *Callee,
John McCall6b51f282009-11-23 01:53:49 +00004927 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004928 Expr **Args, unsigned NumArgs,
4929 OverloadCandidateSet &CandidateSet,
4930 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00004931 if (isa<UsingShadowDecl>(Callee))
4932 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
4933
Douglas Gregorcabea402009-09-22 15:41:20 +00004934 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00004935 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregorcabea402009-09-22 15:41:20 +00004936 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4937 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004938 return;
John McCalld14a8642009-11-21 08:51:07 +00004939 }
4940
4941 if (FunctionTemplateDecl *FuncTemplate
4942 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00004943 S.AddTemplateOverloadCandidate(FuncTemplate, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00004944 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00004945 return;
4946 }
4947
4948 assert(false && "unhandled case in overloaded call candidate");
4949
4950 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00004951}
4952
4953/// \brief Add the overload candidates named by callee and/or found by argument
4954/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00004955void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00004956 Expr **Args, unsigned NumArgs,
4957 OverloadCandidateSet &CandidateSet,
4958 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00004959
4960#ifndef NDEBUG
4961 // Verify that ArgumentDependentLookup is consistent with the rules
4962 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00004963 //
Douglas Gregorcabea402009-09-22 15:41:20 +00004964 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4965 // and let Y be the lookup set produced by argument dependent
4966 // lookup (defined as follows). If X contains
4967 //
4968 // -- a declaration of a class member, or
4969 //
4970 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00004971 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00004972 //
4973 // -- a declaration that is neither a function or a function
4974 // template
4975 //
4976 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00004977
John McCall57500772009-12-16 12:17:52 +00004978 if (ULE->requiresADL()) {
4979 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
4980 E = ULE->decls_end(); I != E; ++I) {
4981 assert(!(*I)->getDeclContext()->isRecord());
4982 assert(isa<UsingShadowDecl>(*I) ||
4983 !(*I)->getDeclContext()->isFunctionOrMethod());
4984 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00004985 }
4986 }
4987#endif
4988
John McCall57500772009-12-16 12:17:52 +00004989 // It would be nice to avoid this copy.
4990 TemplateArgumentListInfo TABuffer;
4991 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
4992 if (ULE->hasExplicitTemplateArgs()) {
4993 ULE->copyTemplateArgumentsInto(TABuffer);
4994 ExplicitTemplateArgs = &TABuffer;
4995 }
4996
4997 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
4998 E = ULE->decls_end(); I != E; ++I)
John McCall6b51f282009-11-23 01:53:49 +00004999 AddOverloadedCallCandidate(*this, *I, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005000 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00005001 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00005002
John McCall57500772009-12-16 12:17:52 +00005003 if (ULE->requiresADL())
5004 AddArgumentDependentLookupCandidates(ULE->getName(), Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005005 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005006 CandidateSet,
5007 PartialOverloading);
5008}
John McCalld681c392009-12-16 08:11:27 +00005009
John McCall57500772009-12-16 12:17:52 +00005010static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5011 Expr **Args, unsigned NumArgs) {
5012 Fn->Destroy(SemaRef.Context);
5013 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5014 Args[Arg]->Destroy(SemaRef.Context);
5015 return SemaRef.ExprError();
5016}
5017
John McCalld681c392009-12-16 08:11:27 +00005018/// Attempts to recover from a call where no functions were found.
5019///
5020/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00005021static Sema::OwningExprResult
5022BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn,
5023 UnresolvedLookupExpr *ULE,
5024 SourceLocation LParenLoc,
5025 Expr **Args, unsigned NumArgs,
5026 SourceLocation *CommaLocs,
5027 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00005028
5029 CXXScopeSpec SS;
5030 if (ULE->getQualifier()) {
5031 SS.setScopeRep(ULE->getQualifier());
5032 SS.setRange(ULE->getQualifierRange());
5033 }
5034
John McCall57500772009-12-16 12:17:52 +00005035 TemplateArgumentListInfo TABuffer;
5036 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5037 if (ULE->hasExplicitTemplateArgs()) {
5038 ULE->copyTemplateArgumentsInto(TABuffer);
5039 ExplicitTemplateArgs = &TABuffer;
5040 }
5041
John McCalld681c392009-12-16 08:11:27 +00005042 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5043 Sema::LookupOrdinaryName);
Douglas Gregor598b08f2009-12-31 05:20:13 +00005044 if (SemaRef.DiagnoseEmptyLookup(/*Scope=*/0, SS, R))
John McCall57500772009-12-16 12:17:52 +00005045 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00005046
John McCall57500772009-12-16 12:17:52 +00005047 assert(!R.empty() && "lookup results empty despite recovery");
5048
5049 // Build an implicit member call if appropriate. Just drop the
5050 // casts and such from the call, we don't really care.
5051 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5052 if ((*R.begin())->isCXXClassMember())
5053 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5054 else if (ExplicitTemplateArgs)
5055 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5056 else
5057 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5058
5059 if (NewFn.isInvalid())
5060 return Destroy(SemaRef, Fn, Args, NumArgs);
5061
5062 Fn->Destroy(SemaRef.Context);
5063
5064 // This shouldn't cause an infinite loop because we're giving it
5065 // an expression with non-empty lookup results, which should never
5066 // end up here.
5067 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5068 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5069 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005070}
Douglas Gregorcabea402009-09-22 15:41:20 +00005071
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005072/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00005073/// (which eventually refers to the declaration Func) and the call
5074/// arguments Args/NumArgs, attempt to resolve the function call down
5075/// to a specific function. If overload resolution succeeds, returns
5076/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00005077/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005078/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00005079Sema::OwningExprResult
5080Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE,
5081 SourceLocation LParenLoc,
5082 Expr **Args, unsigned NumArgs,
5083 SourceLocation *CommaLocs,
5084 SourceLocation RParenLoc) {
5085#ifndef NDEBUG
5086 if (ULE->requiresADL()) {
5087 // To do ADL, we must have found an unqualified name.
5088 assert(!ULE->getQualifier() && "qualified name with ADL");
5089
5090 // We don't perform ADL for implicit declarations of builtins.
5091 // Verify that this was correctly set up.
5092 FunctionDecl *F;
5093 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5094 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5095 F->getBuiltinID() && F->isImplicit())
5096 assert(0 && "performing ADL for builtin");
5097
5098 // We don't perform ADL in C.
5099 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5100 }
5101#endif
5102
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005103 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005104
John McCall57500772009-12-16 12:17:52 +00005105 // Add the functions denoted by the callee to the set of candidate
5106 // functions, including those from argument-dependent lookup.
5107 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00005108
5109 // If we found nothing, try to recover.
5110 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5111 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00005112 if (CandidateSet.empty())
5113 return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs,
5114 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005115
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005116 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005117 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00005118 case OR_Success: {
5119 FunctionDecl *FDecl = Best->Function;
5120 Fn = FixOverloadedFunctionReference(Fn, FDecl);
5121 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5122 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005123
5124 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00005125 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005126 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00005127 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005128 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005129 break;
5130
5131 case OR_Ambiguous:
5132 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00005133 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005134 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005135 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005136
5137 case OR_Deleted:
5138 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5139 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00005140 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00005141 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005142 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005143 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005144 }
5145
5146 // Overload resolution failed. Destroy all of the subexpressions and
5147 // return NULL.
5148 Fn->Destroy(Context);
5149 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5150 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00005151 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005152}
5153
John McCall283b9012009-11-22 00:44:51 +00005154static bool IsOverloaded(const Sema::FunctionSet &Functions) {
5155 return Functions.size() > 1 ||
5156 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5157}
5158
Douglas Gregor084d8552009-03-13 23:49:33 +00005159/// \brief Create a unary operation that may resolve to an overloaded
5160/// operator.
5161///
5162/// \param OpLoc The location of the operator itself (e.g., '*').
5163///
5164/// \param OpcIn The UnaryOperator::Opcode that describes this
5165/// operator.
5166///
5167/// \param Functions The set of non-member functions that will be
5168/// considered by overload resolution. The caller needs to build this
5169/// set based on the context using, e.g.,
5170/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5171/// set should not contain any member functions; those will be added
5172/// by CreateOverloadedUnaryOp().
5173///
5174/// \param input The input argument.
5175Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
5176 unsigned OpcIn,
5177 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00005178 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005179 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5180 Expr *Input = (Expr *)input.get();
5181
5182 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5183 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5184 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5185
5186 Expr *Args[2] = { Input, 0 };
5187 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00005188
Douglas Gregor084d8552009-03-13 23:49:33 +00005189 // For post-increment and post-decrement, add the implicit '0' as
5190 // the second argument, so that we know this is a post-increment or
5191 // post-decrement.
5192 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5193 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00005194 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00005195 SourceLocation());
5196 NumArgs = 2;
5197 }
5198
5199 if (Input->isTypeDependent()) {
John McCalld14a8642009-11-21 08:51:07 +00005200 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005201 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5202 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00005203 /*ADL*/ true, IsOverloaded(Functions));
Mike Stump11289f42009-09-09 15:08:12 +00005204 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00005205 FuncEnd = Functions.end();
5206 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00005207 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00005208
Douglas Gregor084d8552009-03-13 23:49:33 +00005209 input.release();
5210 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5211 &Args[0], NumArgs,
5212 Context.DependentTy,
5213 OpLoc));
5214 }
5215
5216 // Build an empty overload set.
5217 OverloadCandidateSet CandidateSet;
5218
5219 // Add the candidates from the given function set.
5220 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
5221
5222 // Add operator candidates that are member functions.
5223 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5224
5225 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005226 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00005227
5228 // Perform overload resolution.
5229 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005230 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005231 case OR_Success: {
5232 // We found a built-in operator or an overloaded operator.
5233 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00005234
Douglas Gregor084d8552009-03-13 23:49:33 +00005235 if (FnDecl) {
5236 // We matched an overloaded operator. Build a call to that
5237 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00005238
Douglas Gregor084d8552009-03-13 23:49:33 +00005239 // Convert the arguments.
5240 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
5241 if (PerformObjectArgumentInitialization(Input, Method))
5242 return ExprError();
5243 } else {
5244 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00005245 OwningExprResult InputInit
5246 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005247 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00005248 SourceLocation(),
5249 move(input));
5250 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00005251 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005252
Douglas Gregore6600372009-12-23 17:40:29 +00005253 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00005254 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00005255 }
5256
5257 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005258 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005259
Douglas Gregor084d8552009-03-13 23:49:33 +00005260 // Build the actual expression node.
5261 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5262 SourceLocation());
5263 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005264
Douglas Gregor084d8552009-03-13 23:49:33 +00005265 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00005266 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005267 ExprOwningPtr<CallExpr> TheCall(this,
5268 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00005269 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00005270
5271 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5272 FnDecl))
5273 return ExprError();
5274
5275 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00005276 } else {
5277 // We matched a built-in operator. Convert the arguments, then
5278 // break out so that we will build the appropriate built-in
5279 // operator node.
5280 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005281 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00005282 return ExprError();
5283
5284 break;
5285 }
5286 }
5287
5288 case OR_No_Viable_Function:
5289 // No viable function; fall through to handling this as a
5290 // built-in operator, which will produce an error message for us.
5291 break;
5292
5293 case OR_Ambiguous:
5294 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5295 << UnaryOperator::getOpcodeStr(Opc)
5296 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005297 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005298 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00005299 return ExprError();
5300
5301 case OR_Deleted:
5302 Diag(OpLoc, diag::err_ovl_deleted_oper)
5303 << Best->Function->isDeleted()
5304 << UnaryOperator::getOpcodeStr(Opc)
5305 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005306 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00005307 return ExprError();
5308 }
5309
5310 // Either we found no viable overloaded operator or we matched a
5311 // built-in operator. In either case, fall through to trying to
5312 // build a built-in operation.
5313 input.release();
5314 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5315}
5316
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005317/// \brief Create a binary operation that may resolve to an overloaded
5318/// operator.
5319///
5320/// \param OpLoc The location of the operator itself (e.g., '+').
5321///
5322/// \param OpcIn The BinaryOperator::Opcode that describes this
5323/// operator.
5324///
5325/// \param Functions The set of non-member functions that will be
5326/// considered by overload resolution. The caller needs to build this
5327/// set based on the context using, e.g.,
5328/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5329/// set should not contain any member functions; those will be added
5330/// by CreateOverloadedBinOp().
5331///
5332/// \param LHS Left-hand argument.
5333/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00005334Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005335Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005336 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005337 FunctionSet &Functions,
5338 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005339 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00005340 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005341
5342 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5343 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5344 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5345
5346 // If either side is type-dependent, create an appropriate dependent
5347 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00005348 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00005349 if (Functions.empty()) {
5350 // If there are no functions to store, just build a dependent
5351 // BinaryOperator or CompoundAssignment.
5352 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5353 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5354 Context.DependentTy, OpLoc));
5355
5356 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5357 Context.DependentTy,
5358 Context.DependentTy,
5359 Context.DependentTy,
5360 OpLoc));
5361 }
5362
John McCalld14a8642009-11-21 08:51:07 +00005363 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005364 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5365 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00005366 /* ADL */ true, IsOverloaded(Functions));
John McCalld14a8642009-11-21 08:51:07 +00005367
Mike Stump11289f42009-09-09 15:08:12 +00005368 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005369 FuncEnd = Functions.end();
5370 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00005371 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00005372
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005373 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00005374 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005375 Context.DependentTy,
5376 OpLoc));
5377 }
5378
5379 // If this is the .* operator, which is not overloadable, just
5380 // create a built-in binary operator.
5381 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00005382 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005383
Sebastian Redl6a96bf72009-11-18 23:10:33 +00005384 // If this is the assignment operator, we only perform overload resolution
5385 // if the left-hand side is a class or enumeration type. This is actually
5386 // a hack. The standard requires that we do overload resolution between the
5387 // various built-in candidates, but as DR507 points out, this can lead to
5388 // problems. So we do it this way, which pretty much follows what GCC does.
5389 // Note that we go the traditional code path for compound assignment forms.
5390 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00005391 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005392
Douglas Gregor084d8552009-03-13 23:49:33 +00005393 // Build an empty overload set.
5394 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005395
5396 // Add the candidates from the given function set.
5397 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
5398
5399 // Add operator candidates that are member functions.
5400 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5401
5402 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005403 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005404
5405 // Perform overload resolution.
5406 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005407 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005408 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005409 // We found a built-in operator or an overloaded operator.
5410 FunctionDecl *FnDecl = Best->Function;
5411
5412 if (FnDecl) {
5413 // We matched an overloaded operator. Build a call to that
5414 // operator.
5415
5416 // Convert the arguments.
5417 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005418 OwningExprResult Arg1
5419 = PerformCopyInitialization(
5420 InitializedEntity::InitializeParameter(
5421 FnDecl->getParamDecl(0)),
5422 SourceLocation(),
5423 Owned(Args[1]));
5424 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005425 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005426
5427 if (PerformObjectArgumentInitialization(Args[0], Method))
5428 return ExprError();
5429
5430 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005431 } else {
5432 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005433 OwningExprResult Arg0
5434 = PerformCopyInitialization(
5435 InitializedEntity::InitializeParameter(
5436 FnDecl->getParamDecl(0)),
5437 SourceLocation(),
5438 Owned(Args[0]));
5439 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005440 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00005441
5442 OwningExprResult Arg1
5443 = PerformCopyInitialization(
5444 InitializedEntity::InitializeParameter(
5445 FnDecl->getParamDecl(1)),
5446 SourceLocation(),
5447 Owned(Args[1]));
5448 if (Arg1.isInvalid())
5449 return ExprError();
5450 Args[0] = LHS = Arg0.takeAs<Expr>();
5451 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005452 }
5453
5454 // Determine the result type
5455 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00005456 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005457 ResultTy = ResultTy.getNonReferenceType();
5458
5459 // Build the actual expression node.
5460 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00005461 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005462 UsualUnaryConversions(FnExpr);
5463
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005464 ExprOwningPtr<CXXOperatorCallExpr>
5465 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5466 Args, 2, ResultTy,
5467 OpLoc));
5468
5469 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5470 FnDecl))
5471 return ExprError();
5472
5473 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005474 } else {
5475 // We matched a built-in operator. Convert the arguments, then
5476 // break out so that we will build the appropriate built-in
5477 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00005478 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005479 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00005480 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005481 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005482 return ExprError();
5483
5484 break;
5485 }
5486 }
5487
Douglas Gregor66950a32009-09-30 21:46:01 +00005488 case OR_No_Viable_Function: {
5489 // C++ [over.match.oper]p9:
5490 // If the operator is the operator , [...] and there are no
5491 // viable functions, then the operator is assumed to be the
5492 // built-in operator and interpreted according to clause 5.
5493 if (Opc == BinaryOperator::Comma)
5494 break;
5495
Sebastian Redl027de2a2009-05-21 11:50:50 +00005496 // For class as left operand for assignment or compound assigment operator
5497 // do not fall through to handling in built-in, but report that no overloaded
5498 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00005499 OwningExprResult Result = ExprError();
5500 if (Args[0]->getType()->isRecordType() &&
5501 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00005502 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5503 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005504 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00005505 } else {
5506 // No viable function; try to create a built-in operation, which will
5507 // produce an error. Then, show the non-viable candidates.
5508 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00005509 }
Douglas Gregor66950a32009-09-30 21:46:01 +00005510 assert(Result.isInvalid() &&
5511 "C++ binary operator overloading is missing candidates!");
5512 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00005513 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005514 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00005515 return move(Result);
5516 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005517
5518 case OR_Ambiguous:
5519 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5520 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005521 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005522 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005523 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005524 return ExprError();
5525
5526 case OR_Deleted:
5527 Diag(OpLoc, diag::err_ovl_deleted_oper)
5528 << Best->Function->isDeleted()
5529 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005530 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005531 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005532 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00005533 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005534
Douglas Gregor66950a32009-09-30 21:46:01 +00005535 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00005536 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005537}
5538
Sebastian Redladba46e2009-10-29 20:17:01 +00005539Action::OwningExprResult
5540Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5541 SourceLocation RLoc,
5542 ExprArg Base, ExprArg Idx) {
5543 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5544 static_cast<Expr*>(Idx.get()) };
5545 DeclarationName OpName =
5546 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5547
5548 // If either side is type-dependent, create an appropriate dependent
5549 // expression.
5550 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5551
John McCalld14a8642009-11-21 08:51:07 +00005552 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005553 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5554 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00005555 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00005556 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00005557
5558 Base.release();
5559 Idx.release();
5560 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5561 Args, 2,
5562 Context.DependentTy,
5563 RLoc));
5564 }
5565
5566 // Build an empty overload set.
5567 OverloadCandidateSet CandidateSet;
5568
5569 // Subscript can only be overloaded as a member function.
5570
5571 // Add operator candidates that are member functions.
5572 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5573
5574 // Add builtin operator candidates.
5575 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5576
5577 // Perform overload resolution.
5578 OverloadCandidateSet::iterator Best;
5579 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5580 case OR_Success: {
5581 // We found a built-in operator or an overloaded operator.
5582 FunctionDecl *FnDecl = Best->Function;
5583
5584 if (FnDecl) {
5585 // We matched an overloaded operator. Build a call to that
5586 // operator.
5587
5588 // Convert the arguments.
5589 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5590 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5591 PerformCopyInitialization(Args[1],
5592 FnDecl->getParamDecl(0)->getType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005593 AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00005594 return ExprError();
5595
5596 // Determine the result type
5597 QualType ResultTy
5598 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5599 ResultTy = ResultTy.getNonReferenceType();
5600
5601 // Build the actual expression node.
5602 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5603 LLoc);
5604 UsualUnaryConversions(FnExpr);
5605
5606 Base.release();
5607 Idx.release();
5608 ExprOwningPtr<CXXOperatorCallExpr>
5609 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5610 FnExpr, Args, 2,
5611 ResultTy, RLoc));
5612
5613 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5614 FnDecl))
5615 return ExprError();
5616
5617 return MaybeBindToTemporary(TheCall.release());
5618 } else {
5619 // We matched a built-in operator. Convert the arguments, then
5620 // break out so that we will build the appropriate built-in
5621 // operator node.
5622 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005623 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00005624 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005625 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00005626 return ExprError();
5627
5628 break;
5629 }
5630 }
5631
5632 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00005633 if (CandidateSet.empty())
5634 Diag(LLoc, diag::err_ovl_no_oper)
5635 << Args[0]->getType() << /*subscript*/ 0
5636 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5637 else
5638 Diag(LLoc, diag::err_ovl_no_viable_subscript)
5639 << Args[0]->getType()
5640 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005641 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00005642 "[]", LLoc);
5643 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00005644 }
5645
5646 case OR_Ambiguous:
5647 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5648 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005649 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00005650 "[]", LLoc);
5651 return ExprError();
5652
5653 case OR_Deleted:
5654 Diag(LLoc, diag::err_ovl_deleted_oper)
5655 << Best->Function->isDeleted() << "[]"
5656 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005657 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00005658 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00005659 return ExprError();
5660 }
5661
5662 // We matched a built-in operator; build it.
5663 Base.release();
5664 Idx.release();
5665 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5666 Owned(Args[1]), RLoc);
5667}
5668
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005669/// BuildCallToMemberFunction - Build a call to a member
5670/// function. MemExpr is the expression that refers to the member
5671/// function (and includes the object parameter), Args/NumArgs are the
5672/// arguments to the function call (not including the object
5673/// parameter). The caller needs to validate that the member
5674/// expression refers to a member function or an overloaded member
5675/// function.
John McCall2d74de92009-12-01 22:10:20 +00005676Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00005677Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5678 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005679 unsigned NumArgs, SourceLocation *CommaLocs,
5680 SourceLocation RParenLoc) {
5681 // Dig out the member expression. This holds both the object
5682 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00005683 Expr *NakedMemExpr = MemExprE->IgnoreParens();
5684
John McCall10eae182009-11-30 22:42:35 +00005685 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005686 CXXMethodDecl *Method = 0;
John McCall10eae182009-11-30 22:42:35 +00005687 if (isa<MemberExpr>(NakedMemExpr)) {
5688 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00005689 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5690 } else {
5691 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
John McCall2d74de92009-12-01 22:10:20 +00005692
John McCall6e9f8f62009-12-03 04:06:58 +00005693 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00005694
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005695 // Add overload candidates
5696 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00005697
John McCall2d74de92009-12-01 22:10:20 +00005698 // FIXME: avoid copy.
5699 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5700 if (UnresExpr->hasExplicitTemplateArgs()) {
5701 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5702 TemplateArgs = &TemplateArgsBuffer;
5703 }
5704
John McCall10eae182009-11-30 22:42:35 +00005705 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
5706 E = UnresExpr->decls_end(); I != E; ++I) {
5707
John McCall6e9f8f62009-12-03 04:06:58 +00005708 NamedDecl *Func = *I;
5709 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
5710 if (isa<UsingShadowDecl>(Func))
5711 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
5712
John McCall10eae182009-11-30 22:42:35 +00005713 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00005714 // If explicit template arguments were provided, we can't call a
5715 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00005716 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00005717 continue;
5718
John McCall6e9f8f62009-12-03 04:06:58 +00005719 AddMethodCandidate(Method, ActingDC, ObjectType, Args, NumArgs,
5720 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005721 } else {
John McCall10eae182009-11-30 22:42:35 +00005722 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall6e9f8f62009-12-03 04:06:58 +00005723 ActingDC, TemplateArgs,
5724 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005725 CandidateSet,
5726 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005727 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005728 }
Mike Stump11289f42009-09-09 15:08:12 +00005729
John McCall10eae182009-11-30 22:42:35 +00005730 DeclarationName DeclName = UnresExpr->getMemberName();
5731
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005732 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00005733 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005734 case OR_Success:
5735 Method = cast<CXXMethodDecl>(Best->Function);
5736 break;
5737
5738 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00005739 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005740 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005741 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005742 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005743 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005744 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005745
5746 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00005747 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005748 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005749 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005750 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005751 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005752
5753 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00005754 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00005755 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00005756 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005757 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005758 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005759 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005760 }
5761
Douglas Gregor51c538b2009-11-20 19:42:02 +00005762 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCall2d74de92009-12-01 22:10:20 +00005763
John McCall2d74de92009-12-01 22:10:20 +00005764 // If overload resolution picked a static member, build a
5765 // non-member call based on that function.
5766 if (Method->isStatic()) {
5767 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
5768 Args, NumArgs, RParenLoc);
5769 }
5770
John McCall10eae182009-11-30 22:42:35 +00005771 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005772 }
5773
5774 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00005775 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00005776 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00005777 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005778 Method->getResultType().getNonReferenceType(),
5779 RParenLoc));
5780
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005781 // Check for a valid return type.
5782 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5783 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00005784 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005785
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005786 // Convert the object argument (for a non-static member function call).
John McCall2d74de92009-12-01 22:10:20 +00005787 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00005788 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005789 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCall2d74de92009-12-01 22:10:20 +00005790 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005791 MemExpr->setBase(ObjectArg);
5792
5793 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005794 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00005795 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005796 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00005797 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005798
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005799 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00005800 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00005801
John McCall2d74de92009-12-01 22:10:20 +00005802 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005803}
5804
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005805/// BuildCallToObjectOfClassType - Build a call to an object of class
5806/// type (C++ [over.call.object]), which can end up invoking an
5807/// overloaded function call operator (@c operator()) or performing a
5808/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00005809Sema::ExprResult
5810Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00005811 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005812 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00005813 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005814 SourceLocation RParenLoc) {
5815 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005816 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00005817
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005818 // C++ [over.call.object]p1:
5819 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00005820 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005821 // candidate functions includes at least the function call
5822 // operators of T. The function call operators of T are obtained by
5823 // ordinary lookup of the name operator() in the context of
5824 // (E).operator().
5825 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00005826 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005827
5828 if (RequireCompleteType(LParenLoc, Object->getType(),
5829 PartialDiagnostic(diag::err_incomplete_object_call)
5830 << Object->getSourceRange()))
5831 return true;
5832
John McCall27b18f82009-11-17 02:14:36 +00005833 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5834 LookupQualifiedName(R, Record->getDecl());
5835 R.suppressDiagnostics();
5836
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005837 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00005838 Oper != OperEnd; ++Oper) {
John McCall6e9f8f62009-12-03 04:06:58 +00005839 AddMethodCandidate(*Oper, Object->getType(), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005840 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00005841 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005842
Douglas Gregorab7897a2008-11-19 22:57:39 +00005843 // C++ [over.call.object]p2:
5844 // In addition, for each conversion function declared in T of the
5845 // form
5846 //
5847 // operator conversion-type-id () cv-qualifier;
5848 //
5849 // where cv-qualifier is the same cv-qualification as, or a
5850 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00005851 // denotes the type "pointer to function of (P1,...,Pn) returning
5852 // R", or the type "reference to pointer to function of
5853 // (P1,...,Pn) returning R", or the type "reference to function
5854 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00005855 // is also considered as a candidate function. Similarly,
5856 // surrogate call functions are added to the set of candidate
5857 // functions for each conversion function declared in an
5858 // accessible base class provided the function is not hidden
5859 // within T by another intervening declaration.
John McCalld14a8642009-11-21 08:51:07 +00005860 const UnresolvedSet *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00005861 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00005862 for (UnresolvedSet::iterator I = Conversions->begin(),
5863 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00005864 NamedDecl *D = *I;
5865 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5866 if (isa<UsingShadowDecl>(D))
5867 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5868
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005869 // Skip over templated conversion functions; they aren't
5870 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00005871 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005872 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005873
John McCall6e9f8f62009-12-03 04:06:58 +00005874 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00005875
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005876 // Strip the reference type (if any) and then the pointer type (if
5877 // any) to get down to what might be a function type.
5878 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5879 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5880 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005881
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005882 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall6e9f8f62009-12-03 04:06:58 +00005883 AddSurrogateCandidate(Conv, ActingContext, Proto,
5884 Object->getType(), Args, NumArgs,
5885 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00005886 }
Mike Stump11289f42009-09-09 15:08:12 +00005887
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005888 // Perform overload resolution.
5889 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005890 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005891 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00005892 // Overload resolution succeeded; we'll build the appropriate call
5893 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005894 break;
5895
5896 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00005897 if (CandidateSet.empty())
5898 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
5899 << Object->getType() << /*call*/ 1
5900 << Object->getSourceRange();
5901 else
5902 Diag(Object->getSourceRange().getBegin(),
5903 diag::err_ovl_no_viable_object_call)
5904 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005905 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005906 break;
5907
5908 case OR_Ambiguous:
5909 Diag(Object->getSourceRange().getBegin(),
5910 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005911 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005912 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005913 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005914
5915 case OR_Deleted:
5916 Diag(Object->getSourceRange().getBegin(),
5917 diag::err_ovl_deleted_object_call)
5918 << Best->Function->isDeleted()
5919 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00005920 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00005921 break;
Mike Stump11289f42009-09-09 15:08:12 +00005922 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005923
Douglas Gregorab7897a2008-11-19 22:57:39 +00005924 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005925 // We had an error; delete all of the subexpressions and return
5926 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00005927 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005928 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00005929 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005930 return true;
5931 }
5932
Douglas Gregorab7897a2008-11-19 22:57:39 +00005933 if (Best->Function == 0) {
5934 // Since there is no function declaration, this is one of the
5935 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00005936 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00005937 = cast<CXXConversionDecl>(
5938 Best->Conversions[0].UserDefined.ConversionFunction);
5939
5940 // We selected one of the surrogate functions that converts the
5941 // object parameter to a function pointer. Perform the conversion
5942 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005943
5944 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005945 // and then call it.
Eli Friedmana958a012009-12-09 04:52:43 +00005946 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005947
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005948 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005949 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5950 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005951 }
5952
5953 // We found an overloaded operator(). Build a CXXOperatorCallExpr
5954 // that calls this method, using Object for the implicit object
5955 // parameter and passing along the remaining arguments.
5956 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00005957 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005958
5959 unsigned NumArgsInProto = Proto->getNumArgs();
5960 unsigned NumArgsToCheck = NumArgs;
5961
5962 // Build the full argument list for the method call (the
5963 // implicit object parameter is placed at the beginning of the
5964 // list).
5965 Expr **MethodArgs;
5966 if (NumArgs < NumArgsInProto) {
5967 NumArgsToCheck = NumArgsInProto;
5968 MethodArgs = new Expr*[NumArgsInProto + 1];
5969 } else {
5970 MethodArgs = new Expr*[NumArgs + 1];
5971 }
5972 MethodArgs[0] = Object;
5973 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5974 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00005975
5976 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00005977 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005978 UsualUnaryConversions(NewFn);
5979
5980 // Once we've built TheCall, all of the expressions are properly
5981 // owned.
5982 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005983 ExprOwningPtr<CXXOperatorCallExpr>
5984 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005985 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00005986 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005987 delete [] MethodArgs;
5988
Anders Carlsson3d5829c2009-10-13 21:49:31 +00005989 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5990 Method))
5991 return true;
5992
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005993 // We may have default arguments. If so, we need to allocate more
5994 // slots in the call for them.
5995 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00005996 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005997 else if (NumArgs > NumArgsInProto)
5998 NumArgsToCheck = NumArgsInProto;
5999
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006000 bool IsError = false;
6001
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006002 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006003 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006004 TheCall->setArg(0, Object);
6005
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006006
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006007 // Check the argument types.
6008 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006009 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006010 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006011 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00006012
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006013 // Pass the argument.
6014 QualType ProtoArgType = Proto->getArgType(i);
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006015 IsError |= PerformCopyInitialization(Arg, ProtoArgType, AA_Passing);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006016 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00006017 OwningExprResult DefArg
6018 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6019 if (DefArg.isInvalid()) {
6020 IsError = true;
6021 break;
6022 }
6023
6024 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006025 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006026
6027 TheCall->setArg(i + 1, Arg);
6028 }
6029
6030 // If this is a variadic call, handle args passed through "...".
6031 if (Proto->isVariadic()) {
6032 // Promote the arguments (C99 6.5.2.2p7).
6033 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6034 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006035 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006036 TheCall->setArg(i + 1, Arg);
6037 }
6038 }
6039
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006040 if (IsError) return true;
6041
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006042 if (CheckFunctionCall(Method, TheCall.get()))
6043 return true;
6044
Anders Carlsson1c83deb2009-08-16 03:53:54 +00006045 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006046}
6047
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006048/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00006049/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006050/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00006051Sema::OwningExprResult
6052Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6053 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006054 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00006055
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006056 // C++ [over.ref]p1:
6057 //
6058 // [...] An expression x->m is interpreted as (x.operator->())->m
6059 // for a class object x of type T if T::operator->() exists and if
6060 // the operator is selected as the best match function by the
6061 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006062 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
6063 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006064 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00006065
Eli Friedman132e70b2009-11-18 01:28:03 +00006066 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
6067 PDiag(diag::err_typecheck_incomplete_tag)
6068 << Base->getSourceRange()))
6069 return ExprError();
6070
John McCall27b18f82009-11-17 02:14:36 +00006071 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6072 LookupQualifiedName(R, BaseRecord->getDecl());
6073 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00006074
6075 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00006076 Oper != OperEnd; ++Oper) {
6077 NamedDecl *D = *Oper;
6078 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6079 if (isa<UsingShadowDecl>(D))
6080 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6081
6082 AddMethodCandidate(cast<CXXMethodDecl>(D), ActingContext,
6083 Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006084 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00006085 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006086
6087 // Perform overload resolution.
6088 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006089 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006090 case OR_Success:
6091 // Overload resolution succeeded; we'll build the call below.
6092 break;
6093
6094 case OR_No_Viable_Function:
6095 if (CandidateSet.empty())
6096 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00006097 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006098 else
6099 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00006100 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006101 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006102 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006103
6104 case OR_Ambiguous:
6105 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00006106 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006107 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006108 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006109
6110 case OR_Deleted:
6111 Diag(OpLoc, diag::err_ovl_deleted_oper)
6112 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00006113 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006114 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00006115 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006116 }
6117
6118 // Convert the object parameter.
6119 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00006120 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00006121 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00006122
6123 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00006124 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006125
6126 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00006127 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6128 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006129 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006130
6131 QualType ResultTy = Method->getResultType().getNonReferenceType();
6132 ExprOwningPtr<CXXOperatorCallExpr>
6133 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6134 &Base, 1, ResultTy, OpLoc));
6135
6136 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6137 Method))
6138 return ExprError();
6139 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006140}
6141
Douglas Gregorcd695e52008-11-10 20:40:00 +00006142/// FixOverloadedFunctionReference - E is an expression that refers to
6143/// a C++ overloaded function (possibly with some parentheses and
6144/// perhaps a '&' around it). We have resolved the overloaded function
6145/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006146/// refer (possibly indirectly) to Fn. Returns the new expr.
6147Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006148 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor51c538b2009-11-20 19:42:02 +00006149 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
6150 if (SubExpr == PE->getSubExpr())
6151 return PE->Retain();
6152
6153 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6154 }
6155
6156 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6157 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00006158 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00006159 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00006160 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00006161 if (SubExpr == ICE->getSubExpr())
6162 return ICE->Retain();
6163
6164 return new (Context) ImplicitCastExpr(ICE->getType(),
6165 ICE->getCastKind(),
6166 SubExpr,
6167 ICE->isLvalueCast());
6168 }
6169
6170 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00006171 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00006172 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006173 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6174 if (Method->isStatic()) {
6175 // Do nothing: static member functions aren't any different
6176 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00006177 } else {
John McCalle66edc12009-11-24 19:00:30 +00006178 // Fix the sub expression, which really has to be an
6179 // UnresolvedLookupExpr holding an overloaded member function
6180 // or template.
John McCalld14a8642009-11-21 08:51:07 +00006181 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6182 if (SubExpr == UnOp->getSubExpr())
6183 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00006184
John McCalld14a8642009-11-21 08:51:07 +00006185 assert(isa<DeclRefExpr>(SubExpr)
6186 && "fixed to something other than a decl ref");
6187 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6188 && "fixed to a member ref with no nested name qualifier");
6189
6190 // We have taken the address of a pointer to member
6191 // function. Perform the computation here so that we get the
6192 // appropriate pointer to member type.
6193 QualType ClassType
6194 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6195 QualType MemPtrType
6196 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6197
6198 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6199 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00006200 }
6201 }
Douglas Gregor51c538b2009-11-20 19:42:02 +00006202 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6203 if (SubExpr == UnOp->getSubExpr())
6204 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00006205
Douglas Gregor51c538b2009-11-20 19:42:02 +00006206 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6207 Context.getPointerType(SubExpr->getType()),
6208 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00006209 }
John McCalld14a8642009-11-21 08:51:07 +00006210
6211 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00006212 // FIXME: avoid copy.
6213 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00006214 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00006215 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6216 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00006217 }
6218
John McCalld14a8642009-11-21 08:51:07 +00006219 return DeclRefExpr::Create(Context,
6220 ULE->getQualifier(),
6221 ULE->getQualifierRange(),
6222 Fn,
6223 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006224 Fn->getType(),
6225 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00006226 }
6227
John McCall10eae182009-11-30 22:42:35 +00006228 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00006229 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00006230 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6231 if (MemExpr->hasExplicitTemplateArgs()) {
6232 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6233 TemplateArgs = &TemplateArgsBuffer;
6234 }
John McCall6b51f282009-11-23 01:53:49 +00006235
John McCall2d74de92009-12-01 22:10:20 +00006236 Expr *Base;
6237
6238 // If we're filling in
6239 if (MemExpr->isImplicitAccess()) {
6240 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6241 return DeclRefExpr::Create(Context,
6242 MemExpr->getQualifier(),
6243 MemExpr->getQualifierRange(),
6244 Fn,
6245 MemExpr->getMemberLoc(),
6246 Fn->getType(),
6247 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00006248 } else {
6249 SourceLocation Loc = MemExpr->getMemberLoc();
6250 if (MemExpr->getQualifier())
6251 Loc = MemExpr->getQualifierRange().getBegin();
6252 Base = new (Context) CXXThisExpr(Loc,
6253 MemExpr->getBaseType(),
6254 /*isImplicit=*/true);
6255 }
John McCall2d74de92009-12-01 22:10:20 +00006256 } else
6257 Base = MemExpr->getBase()->Retain();
6258
6259 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006260 MemExpr->isArrow(),
6261 MemExpr->getQualifier(),
6262 MemExpr->getQualifierRange(),
6263 Fn,
John McCall6b51f282009-11-23 01:53:49 +00006264 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00006265 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00006266 Fn->getType());
6267 }
6268
Douglas Gregor51c538b2009-11-20 19:42:02 +00006269 assert(false && "Invalid reference to overloaded function");
6270 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00006271}
6272
Douglas Gregor3e1e5272009-12-09 23:02:17 +00006273Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
6274 FunctionDecl *Fn) {
6275 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
6276}
6277
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006278} // end namespace clang