blob: acfc32623644d86998d6669327b338b874cacab9 [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"
Douglas Gregor39c16d42008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000022#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000023#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000025#include "llvm/Support/Compiler.h"
26#include <algorithm>
Torok Edwindb714922009-08-24 13:25:12 +000027#include <cstdio>
Douglas Gregor5251f1b2008-10-21 16:13:35 +000028
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
41 ICC_Qualification_Adjustment,
42 ICC_Promotion,
43 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000044 ICC_Promotion,
45 ICC_Conversion,
46 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000047 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000052 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000053 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000054 ICC_Conversion
55 };
56 return Category[(int)Kind];
57}
58
59/// GetConversionRank - Retrieve the implicit conversion rank
60/// corresponding to the given implicit conversion kind.
61ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
62 static const ImplicitConversionRank
63 Rank[(int)ICK_Num_Conversion_Kinds] = {
64 ICR_Exact_Match,
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Promotion,
70 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000071 ICR_Promotion,
72 ICR_Conversion,
73 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000074 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000079 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000080 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000081 ICR_Conversion
82 };
83 return Rank[(int)Kind];
84}
85
86/// GetImplicitConversionName - Return the name of this kind of
87/// implicit conversion.
88const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
89 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
90 "No conversion",
91 "Lvalue-to-rvalue",
92 "Array-to-pointer",
93 "Function-to-pointer",
94 "Qualification",
95 "Integral promotion",
96 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +000097 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +000098 "Integral conversion",
99 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000100 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 "Floating-integral conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000102 "Complex-real conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000103 "Pointer conversion",
104 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000105 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000106 "Compatible-types conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000107 "Derived-to-base conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000108 };
109 return Name[Kind];
110}
111
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000112/// StandardConversionSequence - Set the standard conversion
113/// sequence to the identity conversion.
114void StandardConversionSequence::setAsIdentityConversion() {
115 First = ICK_Identity;
116 Second = ICK_Identity;
117 Third = ICK_Identity;
118 Deprecated = false;
119 ReferenceBinding = false;
120 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000121 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000122 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000123}
124
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000125/// getRank - Retrieve the rank of this standard conversion sequence
126/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
127/// implicit conversions.
128ImplicitConversionRank StandardConversionSequence::getRank() const {
129 ImplicitConversionRank Rank = ICR_Exact_Match;
130 if (GetConversionRank(First) > Rank)
131 Rank = GetConversionRank(First);
132 if (GetConversionRank(Second) > Rank)
133 Rank = GetConversionRank(Second);
134 if (GetConversionRank(Third) > Rank)
135 Rank = GetConversionRank(Third);
136 return Rank;
137}
138
139/// isPointerConversionToBool - Determines whether this conversion is
140/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000141/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000142/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000143bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000144 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
145 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
146
147 // Note that FromType has not necessarily been transformed by the
148 // array-to-pointer or function-to-pointer implicit conversions, so
149 // check for their presence as well as checking whether FromType is
150 // a pointer.
151 if (ToType->isBooleanType() &&
Douglas Gregor033f56d2008-12-23 00:53:59 +0000152 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000153 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154 return true;
155
156 return false;
157}
158
Douglas Gregor5c407d92008-10-23 00:40:37 +0000159/// isPointerConversionToVoidPointer - Determines whether this
160/// conversion is a conversion of a pointer to a void pointer. This is
161/// used as part of the ranking of standard conversion sequences (C++
162/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000163bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
Douglas Gregor5c407d92008-10-23 00:40:37 +0000166 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
167 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
168
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
174
175 if (Second == ICK_Pointer_Conversion)
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
185 bool PrintedSomething = false;
186 if (First != ICK_Identity) {
187 fprintf(stderr, "%s", GetImplicitConversionName(First));
188 PrintedSomething = true;
189 }
190
191 if (Second != ICK_Identity) {
192 if (PrintedSomething) {
193 fprintf(stderr, " -> ");
194 }
195 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor2fe98832008-11-03 19:09:14 +0000196
197 if (CopyConstructor) {
198 fprintf(stderr, " (by copy constructor)");
199 } else if (DirectBinding) {
200 fprintf(stderr, " (direct reference binding)");
201 } else if (ReferenceBinding) {
202 fprintf(stderr, " (reference binding)");
203 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000204 PrintedSomething = true;
205 }
206
207 if (Third != ICK_Identity) {
208 if (PrintedSomething) {
209 fprintf(stderr, " -> ");
210 }
211 fprintf(stderr, "%s", GetImplicitConversionName(Third));
212 PrintedSomething = true;
213 }
214
215 if (!PrintedSomething) {
216 fprintf(stderr, "No conversions required");
217 }
218}
219
220/// DebugPrint - Print this user-defined conversion sequence to standard
221/// error. Useful for debugging overloading issues.
222void UserDefinedConversionSequence::DebugPrint() const {
223 if (Before.First || Before.Second || Before.Third) {
224 Before.DebugPrint();
225 fprintf(stderr, " -> ");
226 }
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000227 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000228 if (After.First || After.Second || After.Third) {
229 fprintf(stderr, " -> ");
230 After.DebugPrint();
231 }
232}
233
234/// DebugPrint - Print this implicit conversion sequence to standard
235/// error. Useful for debugging overloading issues.
236void ImplicitConversionSequence::DebugPrint() const {
237 switch (ConversionKind) {
238 case StandardConversion:
239 fprintf(stderr, "Standard conversion: ");
240 Standard.DebugPrint();
241 break;
242 case UserDefinedConversion:
243 fprintf(stderr, "User-defined conversion: ");
244 UserDefined.DebugPrint();
245 break;
246 case EllipsisConversion:
247 fprintf(stderr, "Ellipsis conversion");
248 break;
249 case BadConversion:
250 fprintf(stderr, "Bad conversion");
251 break;
252 }
253
254 fprintf(stderr, "\n");
255}
256
257// IsOverload - Determine whether the given New declaration is an
258// overload of the Old declaration. This routine returns false if New
259// and Old cannot be overloaded, e.g., if they are functions with the
260// same signature (C++ 1.3.10) or if the Old declaration isn't a
261// function (or overload set). When it does return false and Old is an
262// OverloadedFunctionDecl, MatchedDecl will be set to point to the
Mike Stump11289f42009-09-09 15:08:12 +0000263// FunctionDecl that New cannot be overloaded with.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000264//
265// Example: Given the following input:
266//
267// void f(int, float); // #1
268// void f(int, int); // #2
269// int f(int, int); // #3
270//
271// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000272// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000273//
274// When we process #2, Old is a FunctionDecl for #1. By comparing the
275// parameter types, we see that #1 and #2 are overloaded (since they
276// have different signatures), so this routine returns false;
277// MatchedDecl is unchanged.
278//
279// When we process #3, Old is an OverloadedFunctionDecl containing #1
280// and #2. We compare the signatures of #3 to #1 (they're overloaded,
281// so we do nothing) and then #3 to #2. Since the signatures of #3 and
282// #2 are identical (return types of functions are not part of the
283// signature), IsOverload returns false and MatchedDecl will be set to
284// point to the FunctionDecl for #2.
285bool
Mike Stump11289f42009-09-09 15:08:12 +0000286Sema::IsOverload(FunctionDecl *New, Decl* OldD,
287 OverloadedFunctionDecl::function_iterator& MatchedDecl) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000288 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
289 // Is this new function an overload of every function in the
290 // overload set?
291 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
292 FuncEnd = Ovl->function_end();
293 for (; Func != FuncEnd; ++Func) {
294 if (!IsOverload(New, *Func, MatchedDecl)) {
295 MatchedDecl = Func;
296 return false;
297 }
298 }
299
300 // This function overloads every function in the overload set.
301 return true;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000302 } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
303 return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
304 else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
Douglas Gregor23061de2009-06-24 16:50:40 +0000305 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
Mike Stump11289f42009-09-09 15:08:12 +0000306 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
307
Douglas Gregor23061de2009-06-24 16:50:40 +0000308 // C++ [temp.fct]p2:
309 // A function template can be overloaded with other function templates
310 // and with normal (non-template) functions.
311 if ((OldTemplate == 0) != (NewTemplate == 0))
312 return true;
313
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000314 // Is the function New an overload of the function Old?
315 QualType OldQType = Context.getCanonicalType(Old->getType());
316 QualType NewQType = Context.getCanonicalType(New->getType());
317
318 // Compare the signatures (C++ 1.3.10) of the two functions to
319 // determine whether they are overloads. If we find any mismatch
320 // in the signature, they are overloads.
321
322 // If either of these functions is a K&R-style function (no
323 // prototype), then we consider them to have matching signatures.
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000324 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
325 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000326 return false;
327
Douglas Gregor23061de2009-06-24 16:50:40 +0000328 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
329 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000330
331 // The signature of a function includes the types of its
332 // parameters (C++ 1.3.10), which includes the presence or absence
333 // of the ellipsis; see C++ DR 357).
334 if (OldQType != NewQType &&
335 (OldType->getNumArgs() != NewType->getNumArgs() ||
336 OldType->isVariadic() != NewType->isVariadic() ||
337 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
338 NewType->arg_type_begin())))
339 return true;
340
Douglas Gregor23061de2009-06-24 16:50:40 +0000341 // C++ [temp.over.link]p4:
Mike Stump11289f42009-09-09 15:08:12 +0000342 // The signature of a function template consists of its function
Douglas Gregor23061de2009-06-24 16:50:40 +0000343 // signature, its return type and its template parameter list. The names
344 // of the template parameters are significant only for establishing the
Mike Stump11289f42009-09-09 15:08:12 +0000345 // relationship between the template parameters and the rest of the
Douglas Gregor23061de2009-06-24 16:50:40 +0000346 // signature.
347 //
348 // We check the return type and template parameter lists for function
349 // templates first; the remaining checks follow.
350 if (NewTemplate &&
Mike Stump11289f42009-09-09 15:08:12 +0000351 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
352 OldTemplate->getTemplateParameters(),
Douglas Gregor23061de2009-06-24 16:50:40 +0000353 false, false, SourceLocation()) ||
354 OldType->getResultType() != NewType->getResultType()))
355 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000356
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000357 // If the function is a class member, its signature includes the
358 // cv-qualifiers (if any) on the function itself.
359 //
360 // As part of this, also check whether one of the member functions
361 // is static, in which case they are not overloads (C++
362 // 13.1p2). While not part of the definition of the signature,
363 // this check is important to determine whether these functions
364 // can be overloaded.
365 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
366 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Mike Stump11289f42009-09-09 15:08:12 +0000367 if (OldMethod && NewMethod &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000368 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb81897c2008-11-21 15:36:28 +0000369 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000370 return true;
371
372 // The signatures match; this is not an overload.
373 return false;
374 } else {
375 // (C++ 13p1):
376 // Only function declarations can be overloaded; object and type
377 // declarations cannot be overloaded.
378 return false;
379 }
380}
381
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000382/// TryImplicitConversion - Attempt to perform an implicit conversion
383/// from the given expression (Expr) to the given type (ToType). This
384/// function returns an implicit conversion sequence that can be used
385/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000386///
387/// void f(float f);
388/// void g(int i) { f(i); }
389///
390/// this routine would produce an implicit conversion sequence to
391/// describe the initialization of f from i, which will be a standard
392/// conversion sequence containing an lvalue-to-rvalue conversion (C++
393/// 4.1) followed by a floating-integral conversion (C++ 4.9).
394//
395/// Note that this routine only determines how the conversion can be
396/// performed; it does not actually perform the conversion. As such,
397/// it will not produce any diagnostics if no conversion is available,
398/// but will instead return an implicit conversion sequence of kind
399/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000400///
401/// If @p SuppressUserConversions, then user-defined conversions are
402/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000403/// If @p AllowExplicit, then explicit user-defined conversions are
404/// permitted.
Sebastian Redl42e92c42009-04-12 17:16:29 +0000405/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
406/// no matter its actual lvalueness.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000407ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000408Sema::TryImplicitConversion(Expr* From, QualType ToType,
409 bool SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +0000410 bool AllowExplicit, bool ForceRValue,
Mike Stump11289f42009-09-09 15:08:12 +0000411 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000412 ImplicitConversionSequence ICS;
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000413 OverloadCandidateSet Conversions;
Anders Carlsson228eea32009-08-28 15:33:32 +0000414 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000415 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000416 else if (getLangOptions().CPlusPlus &&
Mike Stump11289f42009-09-09 15:08:12 +0000417 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000418 Conversions,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000419 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +0000420 ForceRValue) == OR_Success) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000421 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor05379422008-11-03 17:51:48 +0000422 // C++ [over.ics.user]p4:
423 // A conversion of an expression of class type to the same class
424 // type is given Exact Match rank, and a conversion of an
425 // expression of class type to a base class of that type is
426 // given Conversion rank, in spite of the fact that a copy
427 // constructor (i.e., a user-defined conversion function) is
428 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000429 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000430 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000431 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000432 = Context.getCanonicalType(From->getType().getUnqualifiedType());
433 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
434 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000435 // Turn this into a "standard" conversion sequence, so that it
436 // gets ranked with standard conversion sequences.
Douglas Gregor05379422008-11-03 17:51:48 +0000437 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
438 ICS.Standard.setAsIdentityConversion();
439 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
440 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000441 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000442 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000443 ICS.Standard.Second = ICK_Derived_To_Base;
444 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000445 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000446
447 // C++ [over.best.ics]p4:
448 // However, when considering the argument of a user-defined
449 // conversion function that is a candidate by 13.3.1.3 when
450 // invoked for the copying of the temporary in the second step
451 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
452 // 13.3.1.6 in all cases, only standard conversion sequences and
453 // ellipsis conversion sequences are allowed.
454 if (SuppressUserConversions &&
455 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
456 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor05379422008-11-03 17:51:48 +0000457 } else
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000458 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000459
460 return ICS;
461}
462
463/// IsStandardConversion - Determines whether there is a standard
464/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
465/// expression From to the type ToType. Standard conversion sequences
466/// only consider non-class types; for conversions that involve class
467/// types, use TryImplicitConversion. If a conversion exists, SCS will
468/// contain the standard conversion sequence required to perform this
469/// conversion and this routine will return true. Otherwise, this
470/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000471bool
472Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000473 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000474 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000475 QualType FromType = From->getType();
476
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000477 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000478 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000479 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000480 SCS.IncompatibleObjC = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000481 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000482 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000483
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000484 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000485 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000486 if (FromType->isRecordType() || ToType->isRecordType()) {
487 if (getLangOptions().CPlusPlus)
488 return false;
489
Mike Stump11289f42009-09-09 15:08:12 +0000490 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000491 }
492
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000493 // The first conversion can be an lvalue-to-rvalue conversion,
494 // array-to-pointer conversion, or function-to-pointer conversion
495 // (C++ 4p1).
496
Mike Stump11289f42009-09-09 15:08:12 +0000497 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000498 // An lvalue (3.10) of a non-function, non-array type T can be
499 // converted to an rvalue.
500 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000501 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000502 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000503 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000504 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000505
506 // If T is a non-class type, the type of the rvalue is the
507 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000508 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
509 // just strip the qualifiers because they don't matter.
510
511 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000512 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000513 } else if (FromType->isArrayType()) {
514 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000515 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000516
517 // An lvalue or rvalue of type "array of N T" or "array of unknown
518 // bound of T" can be converted to an rvalue of type "pointer to
519 // T" (C++ 4.2p1).
520 FromType = Context.getArrayDecayedType(FromType);
521
522 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
523 // This conversion is deprecated. (C++ D.4).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000524 SCS.Deprecated = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000525
526 // For the purpose of ranking in overload resolution
527 // (13.3.3.1.1), this conversion is considered an
528 // array-to-pointer conversion followed by a qualification
529 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000530 SCS.Second = ICK_Identity;
531 SCS.Third = ICK_Qualification;
532 SCS.ToTypePtr = ToType.getAsOpaquePtr();
533 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000534 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000535 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
536 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000537 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000538
539 // An lvalue of function type T can be converted to an rvalue of
540 // type "pointer to T." The result is a pointer to the
541 // function. (C++ 4.3p1).
542 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000543 } else if (FunctionDecl *Fn
Douglas Gregorcd695e52008-11-10 20:40:00 +0000544 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000545 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000546 SCS.First = ICK_Function_To_Pointer;
547
548 // We were able to resolve the address of the overloaded function,
549 // so we can convert to the type of that function.
550 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000551 if (ToType->isLValueReferenceType())
552 FromType = Context.getLValueReferenceType(FromType);
553 else if (ToType->isRValueReferenceType())
554 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000555 else if (ToType->isMemberPointerType()) {
556 // Resolve address only succeeds if both sides are member pointers,
557 // but it doesn't have to be the same class. See DR 247.
558 // Note that this means that the type of &Derived::fn can be
559 // Ret (Base::*)(Args) if the fn overload actually found is from the
560 // base class, even if it was brought into the derived class via a
561 // using declaration. The standard isn't clear on this issue at all.
562 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
563 FromType = Context.getMemberPointerType(FromType,
564 Context.getTypeDeclType(M->getParent()).getTypePtr());
565 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000566 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000567 } else {
568 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000569 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000570 }
571
572 // The second conversion can be an integral promotion, floating
573 // point promotion, integral conversion, floating point conversion,
574 // floating-integral conversion, pointer conversion,
575 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000576 // For overloading in C, this can also be a "compatible-type"
577 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000578 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000579 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000580 // The unqualified versions of the types are the same: there's no
581 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000582 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000583 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000584 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000585 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000586 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000587 } else if (IsFloatingPointPromotion(FromType, ToType)) {
588 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000589 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000590 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000591 } else if (IsComplexPromotion(FromType, ToType)) {
592 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000593 SCS.Second = ICK_Complex_Promotion;
594 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000595 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000596 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000597 // Integral conversions (C++ 4.7).
598 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000599 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000600 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000601 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
602 // Floating point conversions (C++ 4.8).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000603 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000604 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000605 } else if (FromType->isComplexType() && ToType->isComplexType()) {
606 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000607 SCS.Second = ICK_Complex_Conversion;
608 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000609 } else if ((FromType->isFloatingType() &&
610 ToType->isIntegralType() && (!ToType->isBooleanType() &&
611 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000612 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000613 ToType->isFloatingType())) {
614 // Floating-integral conversions (C++ 4.9).
615 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000616 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000617 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000618 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
619 (ToType->isComplexType() && FromType->isArithmeticType())) {
620 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000621 SCS.Second = ICK_Complex_Real;
622 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000623 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
624 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000625 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000626 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000627 SCS.IncompatibleObjC = IncompatibleObjC;
Mike Stump12b8ce12009-08-04 21:02:39 +0000628 } else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
629 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000630 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000631 } else if (ToType->isBooleanType() &&
632 (FromType->isArithmeticType() ||
633 FromType->isEnumeralType() ||
634 FromType->isPointerType() ||
635 FromType->isBlockPointerType() ||
636 FromType->isMemberPointerType() ||
637 FromType->isNullPtrType())) {
638 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000639 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000640 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000641 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000642 Context.typesAreCompatible(ToType, FromType)) {
643 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000644 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000645 } else {
646 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000647 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000648 }
649
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000650 QualType CanonFrom;
651 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000652 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000653 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000654 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000655 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000656 CanonFrom = Context.getCanonicalType(FromType);
657 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000658 } else {
659 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000660 SCS.Third = ICK_Identity;
661
Mike Stump11289f42009-09-09 15:08:12 +0000662 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000663 // [...] Any difference in top-level cv-qualification is
664 // subsumed by the initialization itself and does not constitute
665 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000666 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000667 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000668 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000669 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
670 FromType = ToType;
671 CanonFrom = CanonTo;
672 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000673 }
674
675 // If we have not converted the argument type to the parameter type,
676 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000677 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000678 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000679
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000680 SCS.ToTypePtr = FromType.getAsOpaquePtr();
681 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000682}
683
684/// IsIntegralPromotion - Determines whether the conversion from the
685/// expression From (whose potentially-adjusted type is FromType) to
686/// ToType is an integral promotion (C++ 4.5). If so, returns true and
687/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000688bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000689 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000690 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000691 if (!To) {
692 return false;
693 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000694
695 // An rvalue of type char, signed char, unsigned char, short int, or
696 // unsigned short int can be converted to an rvalue of type int if
697 // int can represent all the values of the source type; otherwise,
698 // the source rvalue can be converted to an rvalue of type unsigned
699 // int (C++ 4.5p1).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000700 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000701 if (// We can promote any signed, promotable integer type to an int
702 (FromType->isSignedIntegerType() ||
703 // We can promote any unsigned integer type whose size is
704 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000705 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000706 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000707 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000708 }
709
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000710 return To->getKind() == BuiltinType::UInt;
711 }
712
713 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
714 // can be converted to an rvalue of the first of the following types
715 // that can represent all the values of its underlying type: int,
716 // unsigned int, long, or unsigned long (C++ 4.5p2).
717 if ((FromType->isEnumeralType() || FromType->isWideCharType())
718 && ToType->isIntegerType()) {
719 // Determine whether the type we're converting from is signed or
720 // unsigned.
721 bool FromIsSigned;
722 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall9dd450b2009-09-21 23:43:11 +0000723 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000724 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
725 FromIsSigned = UnderlyingType->isSignedIntegerType();
726 } else {
727 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
728 FromIsSigned = true;
729 }
730
731 // The types we'll try to promote to, in the appropriate
732 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000733 QualType PromoteTypes[6] = {
734 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000735 Context.LongTy, Context.UnsignedLongTy ,
736 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000737 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000738 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000739 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
740 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000741 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000742 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
743 // We found the type that we can promote to. If this is the
744 // type we wanted, we have a promotion. Otherwise, no
745 // promotion.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000746 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000747 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
748 }
749 }
750 }
751
752 // An rvalue for an integral bit-field (9.6) can be converted to an
753 // rvalue of type int if int can represent all the values of the
754 // bit-field; otherwise, it can be converted to unsigned int if
755 // unsigned int can represent all the values of the bit-field. If
756 // the bit-field is larger yet, no integral promotion applies to
757 // it. If the bit-field has an enumerated type, it is treated as any
758 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000759 // FIXME: We should delay checking of bit-fields until we actually perform the
760 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000761 using llvm::APSInt;
762 if (From)
763 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000764 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000765 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
766 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
767 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
768 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000769
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000770 // Are we promoting to an int from a bitfield that fits in an int?
771 if (BitWidth < ToSize ||
772 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
773 return To->getKind() == BuiltinType::Int;
774 }
Mike Stump11289f42009-09-09 15:08:12 +0000775
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000776 // Are we promoting to an unsigned int from an unsigned bitfield
777 // that fits into an unsigned int?
778 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
779 return To->getKind() == BuiltinType::UInt;
780 }
Mike Stump11289f42009-09-09 15:08:12 +0000781
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000782 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000783 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000784 }
Mike Stump11289f42009-09-09 15:08:12 +0000785
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000786 // An rvalue of type bool can be converted to an rvalue of type int,
787 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000788 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000789 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000790 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000791
792 return false;
793}
794
795/// IsFloatingPointPromotion - Determines whether the conversion from
796/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
797/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000798bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000799 /// An rvalue of type float can be converted to an rvalue of type
800 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000801 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
802 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000803 if (FromBuiltin->getKind() == BuiltinType::Float &&
804 ToBuiltin->getKind() == BuiltinType::Double)
805 return true;
806
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000807 // C99 6.3.1.5p1:
808 // When a float is promoted to double or long double, or a
809 // double is promoted to long double [...].
810 if (!getLangOptions().CPlusPlus &&
811 (FromBuiltin->getKind() == BuiltinType::Float ||
812 FromBuiltin->getKind() == BuiltinType::Double) &&
813 (ToBuiltin->getKind() == BuiltinType::LongDouble))
814 return true;
815 }
816
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000817 return false;
818}
819
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000820/// \brief Determine if a conversion is a complex promotion.
821///
822/// A complex promotion is defined as a complex -> complex conversion
823/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000824/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000825bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000826 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000827 if (!FromComplex)
828 return false;
829
John McCall9dd450b2009-09-21 23:43:11 +0000830 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000831 if (!ToComplex)
832 return false;
833
834 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000835 ToComplex->getElementType()) ||
836 IsIntegralPromotion(0, FromComplex->getElementType(),
837 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000838}
839
Douglas Gregor237f96c2008-11-26 23:31:11 +0000840/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
841/// the pointer type FromPtr to a pointer to type ToPointee, with the
842/// same type qualifiers as FromPtr has on its pointee type. ToType,
843/// if non-empty, will be a pointer to ToType that may or may not have
844/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000845static QualType
846BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000847 QualType ToPointee, QualType ToType,
848 ASTContext &Context) {
849 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
850 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
851 unsigned Quals = CanonFromPointee.getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000852
853 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor237f96c2008-11-26 23:31:11 +0000854 if (CanonToPointee.getCVRQualifiers() == Quals) {
855 // ToType is exactly what we need. Return it.
856 if (ToType.getTypePtr())
857 return ToType;
858
859 // Build a pointer to ToPointee. It has the right qualifiers
860 // already.
861 return Context.getPointerType(ToPointee);
862 }
863
864 // Just build a canonical type that has the right qualifiers.
865 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
866}
867
Mike Stump11289f42009-09-09 15:08:12 +0000868static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000869 bool InOverloadResolution,
870 ASTContext &Context) {
871 // Handle value-dependent integral null pointer constants correctly.
872 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
873 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
874 Expr->getType()->isIntegralType())
875 return !InOverloadResolution;
876
877 return Expr->isNullPointerConstant(Context);
878}
Mike Stump11289f42009-09-09 15:08:12 +0000879
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000880/// IsPointerConversion - Determines whether the conversion of the
881/// expression From, which has the (possibly adjusted) type FromType,
882/// can be converted to the type ToType via a pointer conversion (C++
883/// 4.10). If so, returns true and places the converted type (that
884/// might differ from ToType in its cv-qualifiers at some level) into
885/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000886///
Douglas Gregora29dc052008-11-27 01:19:21 +0000887/// This routine also supports conversions to and from block pointers
888/// and conversions with Objective-C's 'id', 'id<protocols...>', and
889/// pointers to interfaces. FIXME: Once we've determined the
890/// appropriate overloading rules for Objective-C, we may want to
891/// split the Objective-C checks into a different routine; however,
892/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000893/// conversions, so for now they live here. IncompatibleObjC will be
894/// set if the conversion is an allowed Objective-C conversion that
895/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000896bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000897 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000898 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +0000899 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +0000900 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +0000901 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
902 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000903
Mike Stump11289f42009-09-09 15:08:12 +0000904 // Conversion from a null pointer constant to any Objective-C pointer type.
905 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000906 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +0000907 ConvertedType = ToType;
908 return true;
909 }
910
Douglas Gregor231d1c62008-11-27 00:15:41 +0000911 // Blocks: Block pointers can be converted to void*.
912 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000913 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000914 ConvertedType = ToType;
915 return true;
916 }
917 // Blocks: A null pointer constant can be converted to a block
918 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +0000919 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000920 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000921 ConvertedType = ToType;
922 return true;
923 }
924
Sebastian Redl576fd422009-05-10 18:38:11 +0000925 // If the left-hand-side is nullptr_t, the right side can be a null
926 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000927 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000928 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +0000929 ConvertedType = ToType;
930 return true;
931 }
932
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000933 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000934 if (!ToTypePtr)
935 return false;
936
937 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +0000938 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000939 ConvertedType = ToType;
940 return true;
941 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000942
Douglas Gregor237f96c2008-11-26 23:31:11 +0000943 // Beyond this point, both types need to be pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000944 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +0000945 if (!FromTypePtr)
946 return false;
947
948 QualType FromPointeeType = FromTypePtr->getPointeeType();
949 QualType ToPointeeType = ToTypePtr->getPointeeType();
950
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000951 // An rvalue of type "pointer to cv T," where T is an object type,
952 // can be converted to an rvalue of type "pointer to cv void" (C++
953 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +0000954 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000955 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +0000956 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000957 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000958 return true;
959 }
960
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000961 // When we're overloading in C, we allow a special kind of pointer
962 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +0000963 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000964 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000965 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000966 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +0000967 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000968 return true;
969 }
970
Douglas Gregor5c407d92008-10-23 00:40:37 +0000971 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +0000972 //
Douglas Gregor5c407d92008-10-23 00:40:37 +0000973 // An rvalue of type "pointer to cv D," where D is a class type,
974 // can be converted to an rvalue of type "pointer to cv B," where
975 // B is a base class (clause 10) of D. If B is an inaccessible
976 // (clause 11) or ambiguous (10.2) base class of D, a program that
977 // necessitates this conversion is ill-formed. The result of the
978 // conversion is a pointer to the base class sub-object of the
979 // derived class object. The null pointer value is converted to
980 // the null pointer value of the destination type.
981 //
Douglas Gregor39c16d42008-10-24 04:54:22 +0000982 // Note that we do not check for ambiguity or inaccessibility
983 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000984 if (getLangOptions().CPlusPlus &&
985 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor237f96c2008-11-26 23:31:11 +0000986 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000987 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +0000988 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000989 ToType, Context);
990 return true;
991 }
Douglas Gregor5c407d92008-10-23 00:40:37 +0000992
Douglas Gregora119f102008-12-19 19:13:09 +0000993 return false;
994}
995
996/// isObjCPointerConversion - Determines whether this is an
997/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
998/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +0000999bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001000 QualType& ConvertedType,
1001 bool &IncompatibleObjC) {
1002 if (!getLangOptions().ObjC1)
1003 return false;
1004
Steve Naroff7cae42b2009-07-10 23:34:53 +00001005 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001006 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001007 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001008 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001009
Steve Naroff7cae42b2009-07-10 23:34:53 +00001010 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001011 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001012 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001013 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001014 ConvertedType = ToType;
1015 return true;
1016 }
1017 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001018 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001019 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001020 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001021 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001022 ConvertedType = ToType;
1023 return true;
1024 }
1025 // Objective C++: We're able to convert from a pointer to an
1026 // interface to a pointer to a different interface.
1027 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1028 ConvertedType = ToType;
1029 return true;
1030 }
1031
1032 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1033 // Okay: this is some kind of implicit downcast of Objective-C
1034 // interfaces, which is permitted. However, we're going to
1035 // complain about it.
1036 IncompatibleObjC = true;
1037 ConvertedType = FromType;
1038 return true;
1039 }
Mike Stump11289f42009-09-09 15:08:12 +00001040 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001041 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001042 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001043 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001044 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001045 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001046 ToPointeeType = ToBlockPtr->getPointeeType();
1047 else
Douglas Gregora119f102008-12-19 19:13:09 +00001048 return false;
1049
Douglas Gregor033f56d2008-12-23 00:53:59 +00001050 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001051 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001052 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001053 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001054 FromPointeeType = FromBlockPtr->getPointeeType();
1055 else
Douglas Gregora119f102008-12-19 19:13:09 +00001056 return false;
1057
Douglas Gregora119f102008-12-19 19:13:09 +00001058 // If we have pointers to pointers, recursively check whether this
1059 // is an Objective-C conversion.
1060 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1061 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1062 IncompatibleObjC)) {
1063 // We always complain about this conversion.
1064 IncompatibleObjC = true;
1065 ConvertedType = ToType;
1066 return true;
1067 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001068 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001069 // differences in the argument and result types are in Objective-C
1070 // pointer conversions. If so, we permit the conversion (but
1071 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001072 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001073 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001074 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001075 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001076 if (FromFunctionType && ToFunctionType) {
1077 // If the function types are exactly the same, this isn't an
1078 // Objective-C pointer conversion.
1079 if (Context.getCanonicalType(FromPointeeType)
1080 == Context.getCanonicalType(ToPointeeType))
1081 return false;
1082
1083 // Perform the quick checks that will tell us whether these
1084 // function types are obviously different.
1085 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1086 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1087 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1088 return false;
1089
1090 bool HasObjCConversion = false;
1091 if (Context.getCanonicalType(FromFunctionType->getResultType())
1092 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1093 // Okay, the types match exactly. Nothing to do.
1094 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1095 ToFunctionType->getResultType(),
1096 ConvertedType, IncompatibleObjC)) {
1097 // Okay, we have an Objective-C pointer conversion.
1098 HasObjCConversion = true;
1099 } else {
1100 // Function types are too different. Abort.
1101 return false;
1102 }
Mike Stump11289f42009-09-09 15:08:12 +00001103
Douglas Gregora119f102008-12-19 19:13:09 +00001104 // Check argument types.
1105 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1106 ArgIdx != NumArgs; ++ArgIdx) {
1107 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1108 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1109 if (Context.getCanonicalType(FromArgType)
1110 == Context.getCanonicalType(ToArgType)) {
1111 // Okay, the types match exactly. Nothing to do.
1112 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1113 ConvertedType, IncompatibleObjC)) {
1114 // Okay, we have an Objective-C pointer conversion.
1115 HasObjCConversion = true;
1116 } else {
1117 // Argument types are too different. Abort.
1118 return false;
1119 }
1120 }
1121
1122 if (HasObjCConversion) {
1123 // We had an Objective-C conversion. Allow this pointer
1124 // conversion, but complain about it.
1125 ConvertedType = ToType;
1126 IncompatibleObjC = true;
1127 return true;
1128 }
1129 }
1130
Sebastian Redl72b597d2009-01-25 19:43:20 +00001131 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001132}
1133
Douglas Gregor39c16d42008-10-24 04:54:22 +00001134/// CheckPointerConversion - Check the pointer conversion from the
1135/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001136/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001137/// conversions for which IsPointerConversion has already returned
1138/// true. It returns true and produces a diagnostic if there was an
1139/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001140bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
1141 CastExpr::CastKind &Kind) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001142 QualType FromType = From->getType();
1143
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001144 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1145 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001146 QualType FromPointeeType = FromPtrType->getPointeeType(),
1147 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001148
Douglas Gregor39c16d42008-10-24 04:54:22 +00001149 if (FromPointeeType->isRecordType() &&
1150 ToPointeeType->isRecordType()) {
1151 // We must have a derived-to-base conversion. Check an
1152 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001153 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1154 From->getExprLoc(),
1155 From->getSourceRange()))
1156 return true;
1157
1158 // The conversion was successful.
1159 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001160 }
1161 }
Mike Stump11289f42009-09-09 15:08:12 +00001162 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001163 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001164 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001165 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001166 // Objective-C++ conversions are always okay.
1167 // FIXME: We should have a different class of conversions for the
1168 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001169 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001170 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001171
Steve Naroff7cae42b2009-07-10 23:34:53 +00001172 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001173 return false;
1174}
1175
Sebastian Redl72b597d2009-01-25 19:43:20 +00001176/// IsMemberPointerConversion - Determines whether the conversion of the
1177/// expression From, which has the (possibly adjusted) type FromType, can be
1178/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1179/// If so, returns true and places the converted type (that might differ from
1180/// ToType in its cv-qualifiers at some level) into ConvertedType.
1181bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Mike Stump11289f42009-09-09 15:08:12 +00001182 QualType ToType, QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001183 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001184 if (!ToTypePtr)
1185 return false;
1186
1187 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1188 if (From->isNullPointerConstant(Context)) {
1189 ConvertedType = ToType;
1190 return true;
1191 }
1192
1193 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001194 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001195 if (!FromTypePtr)
1196 return false;
1197
1198 // A pointer to member of B can be converted to a pointer to member of D,
1199 // where D is derived from B (C++ 4.11p2).
1200 QualType FromClass(FromTypePtr->getClass(), 0);
1201 QualType ToClass(ToTypePtr->getClass(), 0);
1202 // FIXME: What happens when these are dependent? Is this function even called?
1203
1204 if (IsDerivedFrom(ToClass, FromClass)) {
1205 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1206 ToClass.getTypePtr());
1207 return true;
1208 }
1209
1210 return false;
1211}
1212
1213/// CheckMemberPointerConversion - Check the member pointer conversion from the
1214/// expression From to the type ToType. This routine checks for ambiguous or
1215/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1216/// for which IsMemberPointerConversion has already returned true. It returns
1217/// true and produces a diagnostic if there was an error, or returns false
1218/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001219bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Anders Carlssond7923c62009-08-22 23:33:40 +00001220 CastExpr::CastKind &Kind) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001221 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001222 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001223 if (!FromPtrType) {
1224 // This must be a null pointer to member pointer conversion
Mike Stump11289f42009-09-09 15:08:12 +00001225 assert(From->isNullPointerConstant(Context) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001226 "Expr must be null pointer constant!");
1227 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001228 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001229 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001230
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001231 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001232 assert(ToPtrType && "No member pointer cast has a target type "
1233 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001234
Sebastian Redled8f2002009-01-28 18:33:18 +00001235 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1236 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001237
Sebastian Redled8f2002009-01-28 18:33:18 +00001238 // FIXME: What about dependent types?
1239 assert(FromClass->isRecordType() && "Pointer into non-class.");
1240 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001241
Sebastian Redled8f2002009-01-28 18:33:18 +00001242 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1243 /*DetectVirtual=*/true);
1244 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1245 assert(DerivationOkay &&
1246 "Should not have been called if derivation isn't OK.");
1247 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001248
Sebastian Redled8f2002009-01-28 18:33:18 +00001249 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1250 getUnqualifiedType())) {
1251 // Derivation is ambiguous. Redo the check to find the exact paths.
1252 Paths.clear();
1253 Paths.setRecordingPaths(true);
1254 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1255 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1256 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001257
Sebastian Redled8f2002009-01-28 18:33:18 +00001258 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1259 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1260 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1261 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001262 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001263
Douglas Gregor89ee6822009-02-28 01:32:25 +00001264 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001265 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1266 << FromClass << ToClass << QualType(VBase, 0)
1267 << From->getSourceRange();
1268 return true;
1269 }
1270
Anders Carlssond7923c62009-08-22 23:33:40 +00001271 // Must be a base to derived member conversion.
1272 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001273 return false;
1274}
1275
Douglas Gregor9a657932008-10-21 23:43:52 +00001276/// IsQualificationConversion - Determines whether the conversion from
1277/// an rvalue of type FromType to ToType is a qualification conversion
1278/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001279bool
1280Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001281 FromType = Context.getCanonicalType(FromType);
1282 ToType = Context.getCanonicalType(ToType);
1283
1284 // If FromType and ToType are the same type, this is not a
1285 // qualification conversion.
1286 if (FromType == ToType)
1287 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001288
Douglas Gregor9a657932008-10-21 23:43:52 +00001289 // (C++ 4.4p4):
1290 // A conversion can add cv-qualifiers at levels other than the first
1291 // in multi-level pointers, subject to the following rules: [...]
1292 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001293 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001294 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001295 // Within each iteration of the loop, we check the qualifiers to
1296 // determine if this still looks like a qualification
1297 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001298 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001299 // until there are no more pointers or pointers-to-members left to
1300 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001301 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001302
1303 // -- for every j > 0, if const is in cv 1,j then const is in cv
1304 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001305 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001306 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001307
Douglas Gregor9a657932008-10-21 23:43:52 +00001308 // -- if the cv 1,j and cv 2,j are different, then const is in
1309 // every cv for 0 < k < j.
1310 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001311 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001312 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001313
Douglas Gregor9a657932008-10-21 23:43:52 +00001314 // Keep track of whether all prior cv-qualifiers in the "to" type
1315 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001316 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001317 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001318 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001319
1320 // We are left with FromType and ToType being the pointee types
1321 // after unwrapping the original FromType and ToType the same number
1322 // of types. If we unwrapped any pointers, and if FromType and
1323 // ToType have the same unqualified type (since we checked
1324 // qualifiers above), then this is a qualification conversion.
1325 return UnwrappedAnyPointer &&
1326 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1327}
1328
Douglas Gregor05155d82009-08-21 23:19:43 +00001329/// \brief Given a function template or function, extract the function template
1330/// declaration (if any) and the underlying function declaration.
1331template<typename T>
1332static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1333 FunctionTemplateDecl *&FunctionTemplate) {
1334 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1335 if (FunctionTemplate)
1336 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1337 else
1338 Function = cast<T>(Orig);
1339}
1340
Douglas Gregor576e98c2009-01-30 23:27:23 +00001341/// Determines whether there is a user-defined conversion sequence
1342/// (C++ [over.ics.user]) that converts expression From to the type
1343/// ToType. If such a conversion exists, User will contain the
1344/// user-defined conversion sequence that performs such a conversion
1345/// and this routine will return true. Otherwise, this routine returns
1346/// false and User is unspecified.
1347///
1348/// \param AllowConversionFunctions true if the conversion should
1349/// consider conversion functions at all. If false, only constructors
1350/// will be considered.
1351///
1352/// \param AllowExplicit true if the conversion should consider C++0x
1353/// "explicit" conversion functions as well as non-explicit conversion
1354/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001355///
1356/// \param ForceRValue true if the expression should be treated as an rvalue
1357/// for overload resolution.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001358Sema::OverloadingResult Sema::IsUserDefinedConversion(
1359 Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001360 UserDefinedConversionSequence& User,
Fariborz Jahanian19c73282009-09-15 00:10:11 +00001361 OverloadCandidateSet& CandidateSet,
Douglas Gregor576e98c2009-01-30 23:27:23 +00001362 bool AllowConversionFunctions,
Mike Stump11289f42009-09-09 15:08:12 +00001363 bool AllowExplicit, bool ForceRValue) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001364 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001365 if (CXXRecordDecl *ToRecordDecl
Douglas Gregor89ee6822009-02-28 01:32:25 +00001366 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1367 // C++ [over.match.ctor]p1:
1368 // When objects of class type are direct-initialized (8.5), or
1369 // copy-initialized from an expression of the same or a
1370 // derived class type (8.5), overload resolution selects the
1371 // constructor. [...] For copy-initialization, the candidate
1372 // functions are all the converting constructors (12.3.1) of
1373 // that class. The argument list is the expression-list within
1374 // the parentheses of the initializer.
Mike Stump11289f42009-09-09 15:08:12 +00001375 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001376 = Context.DeclarationNames.getCXXConstructorName(
1377 Context.getCanonicalType(ToType).getUnqualifiedType());
1378 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001379 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001380 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001381 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001382 // Find the constructor (which may be a template).
1383 CXXConstructorDecl *Constructor = 0;
1384 FunctionTemplateDecl *ConstructorTmpl
1385 = dyn_cast<FunctionTemplateDecl>(*Con);
1386 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001387 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001388 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1389 else
1390 Constructor = cast<CXXConstructorDecl>(*Con);
Mike Stump11289f42009-09-09 15:08:12 +00001391
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001392 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001393 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001394 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001395 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001396 1, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00001397 /*SuppressUserConversions=*/true,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001398 ForceRValue);
1399 else
1400 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1401 /*SuppressUserConversions=*/true, ForceRValue);
1402 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001403 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001404 }
1405 }
1406
Douglas Gregor576e98c2009-01-30 23:27:23 +00001407 if (!AllowConversionFunctions) {
1408 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001409 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1410 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001411 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001412 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001413 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001414 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001415 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001416 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1417 // Add all of the conversion functions as candidates.
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001418 OverloadedFunctionDecl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001419 = FromRecordDecl->getVisibleConversionFunctions();
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001420 for (OverloadedFunctionDecl::function_iterator Func
1421 = Conversions->function_begin();
1422 Func != Conversions->function_end(); ++Func) {
1423 CXXConversionDecl *Conv;
1424 FunctionTemplateDecl *ConvTemplate;
1425 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1426 if (ConvTemplate)
1427 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1428 else
1429 Conv = dyn_cast<CXXConversionDecl>(*Func);
1430
1431 if (AllowExplicit || !Conv->isExplicit()) {
1432 if (ConvTemplate)
1433 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1434 CandidateSet);
1435 else
1436 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1437 }
1438 }
1439 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001440 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001441
1442 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001443 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001444 case OR_Success:
1445 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001446 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001447 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1448 // C++ [over.ics.user]p1:
1449 // If the user-defined conversion is specified by a
1450 // constructor (12.3.1), the initial standard conversion
1451 // sequence converts the source type to the type required by
1452 // the argument of the constructor.
1453 //
1454 // FIXME: What about ellipsis conversions?
1455 QualType ThisType = Constructor->getThisType(Context);
1456 User.Before = Best->Conversions[0].Standard;
1457 User.ConversionFunction = Constructor;
1458 User.After.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00001459 User.After.FromTypePtr
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001460 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001461 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001462 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001463 } else if (CXXConversionDecl *Conversion
1464 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1465 // C++ [over.ics.user]p1:
1466 //
1467 // [...] If the user-defined conversion is specified by a
1468 // conversion function (12.3.2), the initial standard
1469 // conversion sequence converts the source type to the
1470 // implicit object parameter of the conversion function.
1471 User.Before = Best->Conversions[0].Standard;
1472 User.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00001473
1474 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001475 // The second standard conversion sequence converts the
1476 // result of the user-defined conversion to the target type
1477 // for the sequence. Since an implicit conversion sequence
1478 // is an initialization, the special rules for
1479 // initialization by user-defined conversion apply when
1480 // selecting the best user-defined conversion for a
1481 // user-defined conversion sequence (see 13.3.3 and
1482 // 13.3.3.1).
1483 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001484 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001485 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001486 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001487 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001488 }
Mike Stump11289f42009-09-09 15:08:12 +00001489
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001490 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001491 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001492 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001493 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001494 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001495
1496 case OR_Ambiguous:
1497 // FIXME: See C++ [over.best.ics]p10 for the handling of
1498 // ambiguous conversion sequences.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001499 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001500 }
1501
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001502 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001503}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001504
1505bool
1506Sema::DiagnoseAmbiguousUserDefinedConversion(Expr *From, QualType ToType) {
1507 ImplicitConversionSequence ICS;
1508 OverloadCandidateSet CandidateSet;
1509 OverloadingResult OvResult =
1510 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1511 CandidateSet, true, false, false);
1512 if (OvResult != OR_Ambiguous)
1513 return false;
1514 Diag(From->getSourceRange().getBegin(),
1515 diag::err_typecheck_ambiguous_condition)
1516 << From->getType() << ToType << From->getSourceRange();
1517 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1518 return true;
1519}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001520
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001521/// CompareImplicitConversionSequences - Compare two implicit
1522/// conversion sequences to determine whether one is better than the
1523/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001524ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001525Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1526 const ImplicitConversionSequence& ICS2)
1527{
1528 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1529 // conversion sequences (as defined in 13.3.3.1)
1530 // -- a standard conversion sequence (13.3.3.1.1) is a better
1531 // conversion sequence than a user-defined conversion sequence or
1532 // an ellipsis conversion sequence, and
1533 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1534 // conversion sequence than an ellipsis conversion sequence
1535 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001536 //
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001537 if (ICS1.ConversionKind < ICS2.ConversionKind)
1538 return ImplicitConversionSequence::Better;
1539 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1540 return ImplicitConversionSequence::Worse;
1541
1542 // Two implicit conversion sequences of the same form are
1543 // indistinguishable conversion sequences unless one of the
1544 // following rules apply: (C++ 13.3.3.2p3):
1545 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1546 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump11289f42009-09-09 15:08:12 +00001547 else if (ICS1.ConversionKind ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001548 ImplicitConversionSequence::UserDefinedConversion) {
1549 // User-defined conversion sequence U1 is a better conversion
1550 // sequence than another user-defined conversion sequence U2 if
1551 // they contain the same user-defined conversion function or
1552 // constructor and if the second standard conversion sequence of
1553 // U1 is better than the second standard conversion sequence of
1554 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001555 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001556 ICS2.UserDefined.ConversionFunction)
1557 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1558 ICS2.UserDefined.After);
1559 }
1560
1561 return ImplicitConversionSequence::Indistinguishable;
1562}
1563
1564/// CompareStandardConversionSequences - Compare two standard
1565/// conversion sequences to determine whether one is better than the
1566/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001567ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001568Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1569 const StandardConversionSequence& SCS2)
1570{
1571 // Standard conversion sequence S1 is a better conversion sequence
1572 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1573
1574 // -- S1 is a proper subsequence of S2 (comparing the conversion
1575 // sequences in the canonical form defined by 13.3.3.1.1,
1576 // excluding any Lvalue Transformation; the identity conversion
1577 // sequence is considered to be a subsequence of any
1578 // non-identity conversion sequence) or, if not that,
1579 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1580 // Neither is a proper subsequence of the other. Do nothing.
1581 ;
1582 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1583 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001584 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001585 SCS1.Third == ICK_Identity))
1586 // SCS1 is a proper subsequence of SCS2.
1587 return ImplicitConversionSequence::Better;
1588 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1589 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001590 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001591 SCS2.Third == ICK_Identity))
1592 // SCS2 is a proper subsequence of SCS1.
1593 return ImplicitConversionSequence::Worse;
1594
1595 // -- the rank of S1 is better than the rank of S2 (by the rules
1596 // defined below), or, if not that,
1597 ImplicitConversionRank Rank1 = SCS1.getRank();
1598 ImplicitConversionRank Rank2 = SCS2.getRank();
1599 if (Rank1 < Rank2)
1600 return ImplicitConversionSequence::Better;
1601 else if (Rank2 < Rank1)
1602 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001603
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001604 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1605 // are indistinguishable unless one of the following rules
1606 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001607
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001608 // A conversion that is not a conversion of a pointer, or
1609 // pointer to member, to bool is better than another conversion
1610 // that is such a conversion.
1611 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1612 return SCS2.isPointerConversionToBool()
1613 ? ImplicitConversionSequence::Better
1614 : ImplicitConversionSequence::Worse;
1615
Douglas Gregor5c407d92008-10-23 00:40:37 +00001616 // C++ [over.ics.rank]p4b2:
1617 //
1618 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001619 // conversion of B* to A* is better than conversion of B* to
1620 // void*, and conversion of A* to void* is better than conversion
1621 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001622 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001623 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001624 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001625 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001626 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1627 // Exactly one of the conversion sequences is a conversion to
1628 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001629 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1630 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001631 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1632 // Neither conversion sequence converts to a void pointer; compare
1633 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001634 if (ImplicitConversionSequence::CompareKind DerivedCK
1635 = CompareDerivedToBaseConversions(SCS1, SCS2))
1636 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001637 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1638 // Both conversion sequences are conversions to void
1639 // pointers. Compare the source types to determine if there's an
1640 // inheritance relationship in their sources.
1641 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1642 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1643
1644 // Adjust the types we're converting from via the array-to-pointer
1645 // conversion, if we need to.
1646 if (SCS1.First == ICK_Array_To_Pointer)
1647 FromType1 = Context.getArrayDecayedType(FromType1);
1648 if (SCS2.First == ICK_Array_To_Pointer)
1649 FromType2 = Context.getArrayDecayedType(FromType2);
1650
Mike Stump11289f42009-09-09 15:08:12 +00001651 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001652 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001653 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001654 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001655
1656 if (IsDerivedFrom(FromPointee2, FromPointee1))
1657 return ImplicitConversionSequence::Better;
1658 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1659 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001660
1661 // Objective-C++: If one interface is more specific than the
1662 // other, it is the better one.
John McCall9dd450b2009-09-21 23:43:11 +00001663 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1664 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001665 if (FromIface1 && FromIface1) {
1666 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1667 return ImplicitConversionSequence::Better;
1668 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1669 return ImplicitConversionSequence::Worse;
1670 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001671 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001672
1673 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1674 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001675 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001676 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001677 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001678
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001679 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001680 // C++0x [over.ics.rank]p3b4:
1681 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1682 // implicit object parameter of a non-static member function declared
1683 // without a ref-qualifier, and S1 binds an rvalue reference to an
1684 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001685 // FIXME: We don't know if we're dealing with the implicit object parameter,
1686 // or if the member function in this case has a ref qualifier.
1687 // (Of course, we don't have ref qualifiers yet.)
1688 if (SCS1.RRefBinding != SCS2.RRefBinding)
1689 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1690 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001691
1692 // C++ [over.ics.rank]p3b4:
1693 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1694 // which the references refer are the same type except for
1695 // top-level cv-qualifiers, and the type to which the reference
1696 // initialized by S2 refers is more cv-qualified than the type
1697 // to which the reference initialized by S1 refers.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001698 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1699 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001700 T1 = Context.getCanonicalType(T1);
1701 T2 = Context.getCanonicalType(T2);
1702 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1703 if (T2.isMoreQualifiedThan(T1))
1704 return ImplicitConversionSequence::Better;
1705 else if (T1.isMoreQualifiedThan(T2))
1706 return ImplicitConversionSequence::Worse;
1707 }
1708 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001709
1710 return ImplicitConversionSequence::Indistinguishable;
1711}
1712
1713/// CompareQualificationConversions - Compares two standard conversion
1714/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001715/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1716ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001717Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001718 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001719 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001720 // -- S1 and S2 differ only in their qualification conversion and
1721 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1722 // cv-qualification signature of type T1 is a proper subset of
1723 // the cv-qualification signature of type T2, and S1 is not the
1724 // deprecated string literal array-to-pointer conversion (4.2).
1725 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1726 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1727 return ImplicitConversionSequence::Indistinguishable;
1728
1729 // FIXME: the example in the standard doesn't use a qualification
1730 // conversion (!)
1731 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1732 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1733 T1 = Context.getCanonicalType(T1);
1734 T2 = Context.getCanonicalType(T2);
1735
1736 // If the types are the same, we won't learn anything by unwrapped
1737 // them.
1738 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1739 return ImplicitConversionSequence::Indistinguishable;
1740
Mike Stump11289f42009-09-09 15:08:12 +00001741 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001742 = ImplicitConversionSequence::Indistinguishable;
1743 while (UnwrapSimilarPointerTypes(T1, T2)) {
1744 // Within each iteration of the loop, we check the qualifiers to
1745 // determine if this still looks like a qualification
1746 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001747 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001748 // until there are no more pointers or pointers-to-members left
1749 // to unwrap. This essentially mimics what
1750 // IsQualificationConversion does, but here we're checking for a
1751 // strict subset of qualifiers.
1752 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1753 // The qualifiers are the same, so this doesn't tell us anything
1754 // about how the sequences rank.
1755 ;
1756 else if (T2.isMoreQualifiedThan(T1)) {
1757 // T1 has fewer qualifiers, so it could be the better sequence.
1758 if (Result == ImplicitConversionSequence::Worse)
1759 // Neither has qualifiers that are a subset of the other's
1760 // qualifiers.
1761 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001762
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001763 Result = ImplicitConversionSequence::Better;
1764 } else if (T1.isMoreQualifiedThan(T2)) {
1765 // T2 has fewer qualifiers, so it could be the better sequence.
1766 if (Result == ImplicitConversionSequence::Better)
1767 // Neither has qualifiers that are a subset of the other's
1768 // qualifiers.
1769 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001770
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001771 Result = ImplicitConversionSequence::Worse;
1772 } else {
1773 // Qualifiers are disjoint.
1774 return ImplicitConversionSequence::Indistinguishable;
1775 }
1776
1777 // If the types after this point are equivalent, we're done.
1778 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1779 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001780 }
1781
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001782 // Check that the winning standard conversion sequence isn't using
1783 // the deprecated string literal array to pointer conversion.
1784 switch (Result) {
1785 case ImplicitConversionSequence::Better:
1786 if (SCS1.Deprecated)
1787 Result = ImplicitConversionSequence::Indistinguishable;
1788 break;
1789
1790 case ImplicitConversionSequence::Indistinguishable:
1791 break;
1792
1793 case ImplicitConversionSequence::Worse:
1794 if (SCS2.Deprecated)
1795 Result = ImplicitConversionSequence::Indistinguishable;
1796 break;
1797 }
1798
1799 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001800}
1801
Douglas Gregor5c407d92008-10-23 00:40:37 +00001802/// CompareDerivedToBaseConversions - Compares two standard conversion
1803/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001804/// various kinds of derived-to-base conversions (C++
1805/// [over.ics.rank]p4b3). As part of these checks, we also look at
1806/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001807ImplicitConversionSequence::CompareKind
1808Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1809 const StandardConversionSequence& SCS2) {
1810 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1811 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1812 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1813 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1814
1815 // Adjust the types we're converting from via the array-to-pointer
1816 // conversion, if we need to.
1817 if (SCS1.First == ICK_Array_To_Pointer)
1818 FromType1 = Context.getArrayDecayedType(FromType1);
1819 if (SCS2.First == ICK_Array_To_Pointer)
1820 FromType2 = Context.getArrayDecayedType(FromType2);
1821
1822 // Canonicalize all of the types.
1823 FromType1 = Context.getCanonicalType(FromType1);
1824 ToType1 = Context.getCanonicalType(ToType1);
1825 FromType2 = Context.getCanonicalType(FromType2);
1826 ToType2 = Context.getCanonicalType(ToType2);
1827
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001828 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001829 //
1830 // If class B is derived directly or indirectly from class A and
1831 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001832 //
1833 // For Objective-C, we let A, B, and C also be Objective-C
1834 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001835
1836 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00001837 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00001838 SCS2.Second == ICK_Pointer_Conversion &&
1839 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1840 FromType1->isPointerType() && FromType2->isPointerType() &&
1841 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001842 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001843 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001844 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001845 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001846 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001847 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001848 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001849 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001850
John McCall9dd450b2009-09-21 23:43:11 +00001851 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1852 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1853 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1854 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001855
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001856 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00001857 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1858 if (IsDerivedFrom(ToPointee1, ToPointee2))
1859 return ImplicitConversionSequence::Better;
1860 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1861 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001862
1863 if (ToIface1 && ToIface2) {
1864 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1865 return ImplicitConversionSequence::Better;
1866 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1867 return ImplicitConversionSequence::Worse;
1868 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001869 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001870
1871 // -- conversion of B* to A* is better than conversion of C* to A*,
1872 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1873 if (IsDerivedFrom(FromPointee2, FromPointee1))
1874 return ImplicitConversionSequence::Better;
1875 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1876 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00001877
Douglas Gregor237f96c2008-11-26 23:31:11 +00001878 if (FromIface1 && FromIface2) {
1879 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1880 return ImplicitConversionSequence::Better;
1881 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1882 return ImplicitConversionSequence::Worse;
1883 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001884 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001885 }
1886
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001887 // Compare based on reference bindings.
1888 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1889 SCS1.Second == ICK_Derived_To_Base) {
1890 // -- binding of an expression of type C to a reference of type
1891 // B& is better than binding an expression of type C to a
1892 // reference of type A&,
1893 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1894 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1895 if (IsDerivedFrom(ToType1, ToType2))
1896 return ImplicitConversionSequence::Better;
1897 else if (IsDerivedFrom(ToType2, ToType1))
1898 return ImplicitConversionSequence::Worse;
1899 }
1900
Douglas Gregor2fe98832008-11-03 19:09:14 +00001901 // -- binding of an expression of type B to a reference of type
1902 // A& is better than binding an expression of type C to a
1903 // reference of type A&,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001904 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1905 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1906 if (IsDerivedFrom(FromType2, FromType1))
1907 return ImplicitConversionSequence::Better;
1908 else if (IsDerivedFrom(FromType1, FromType2))
1909 return ImplicitConversionSequence::Worse;
1910 }
1911 }
1912
1913
1914 // FIXME: conversion of A::* to B::* is better than conversion of
1915 // A::* to C::*,
1916
1917 // FIXME: conversion of B::* to C::* is better than conversion of
1918 // A::* to C::*, and
1919
Douglas Gregor2fe98832008-11-03 19:09:14 +00001920 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1921 SCS1.Second == ICK_Derived_To_Base) {
1922 // -- conversion of C to B is better than conversion of C to A,
1923 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1924 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1925 if (IsDerivedFrom(ToType1, ToType2))
1926 return ImplicitConversionSequence::Better;
1927 else if (IsDerivedFrom(ToType2, ToType1))
1928 return ImplicitConversionSequence::Worse;
1929 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001930
Douglas Gregor2fe98832008-11-03 19:09:14 +00001931 // -- conversion of B to A is better than conversion of C to A.
1932 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1933 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1934 if (IsDerivedFrom(FromType2, FromType1))
1935 return ImplicitConversionSequence::Better;
1936 else if (IsDerivedFrom(FromType1, FromType2))
1937 return ImplicitConversionSequence::Worse;
1938 }
1939 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001940
Douglas Gregor5c407d92008-10-23 00:40:37 +00001941 return ImplicitConversionSequence::Indistinguishable;
1942}
1943
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001944/// TryCopyInitialization - Try to copy-initialize a value of type
1945/// ToType from the expression From. Return the implicit conversion
1946/// sequence required to pass this argument, which may be a bad
1947/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00001948/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00001949/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1950/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00001951ImplicitConversionSequence
1952Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00001953 bool SuppressUserConversions, bool ForceRValue,
1954 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001955 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001956 ImplicitConversionSequence ICS;
Mike Stump11289f42009-09-09 15:08:12 +00001957 CheckReferenceInit(From, ToType,
Anders Carlsson271e3a42009-08-27 17:30:43 +00001958 SuppressUserConversions,
1959 /*AllowExplicit=*/false,
1960 ForceRValue,
1961 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001962 return ICS;
1963 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001964 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00001965 SuppressUserConversions,
1966 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001967 ForceRValue,
1968 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001969 }
1970}
1971
Sebastian Redl42e92c42009-04-12 17:16:29 +00001972/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1973/// the expression @p From. Returns true (and emits a diagnostic) if there was
1974/// an error, returns false if the initialization succeeded. Elidable should
1975/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1976/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00001977bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redl42e92c42009-04-12 17:16:29 +00001978 const char* Flavor, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001979 if (!getLangOptions().CPlusPlus) {
1980 // In C, argument passing is the same as performing an assignment.
1981 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001982
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001983 AssignConvertType ConvTy =
1984 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00001985 if (ConvTy != Compatible &&
1986 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1987 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00001988
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001989 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1990 FromType, From, Flavor);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001991 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00001992
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001993 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00001994 return CheckReferenceInit(From, ToType,
1995 /*SuppressUserConversions=*/false,
1996 /*AllowExplicit=*/false,
1997 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001998
Sebastian Redl42e92c42009-04-12 17:16:29 +00001999 if (!PerformImplicitConversion(From, ToType, Flavor,
2000 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002001 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002002 if (!DiagnoseAmbiguousUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002003 return Diag(From->getSourceRange().getBegin(),
2004 diag::err_typecheck_convert_incompatible)
2005 << ToType << From->getType() << Flavor << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002006 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002007}
2008
Douglas Gregor436424c2008-11-18 23:14:02 +00002009/// TryObjectArgumentInitialization - Try to initialize the object
2010/// parameter of the given member function (@c Method) from the
2011/// expression @p From.
2012ImplicitConversionSequence
2013Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
2014 QualType ClassType = Context.getTypeDeclType(Method->getParent());
2015 unsigned MethodQuals = Method->getTypeQualifiers();
2016 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
2017
2018 // Set up the conversion sequence as a "bad" conversion, to allow us
2019 // to exit early.
2020 ImplicitConversionSequence ICS;
2021 ICS.Standard.setAsIdentityConversion();
2022 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2023
2024 // We need to have an object of class type.
2025 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002026 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002027 FromType = PT->getPointeeType();
2028
2029 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002030
2031 // The implicit object parmeter is has the type "reference to cv X",
2032 // where X is the class of which the function is a member
2033 // (C++ [over.match.funcs]p4). However, when finding an implicit
2034 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002035 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002036 // (C++ [over.match.funcs]p5). We perform a simplified version of
2037 // reference binding here, that allows class rvalues to bind to
2038 // non-constant references.
2039
2040 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2041 // with the implicit object parameter (C++ [over.match.funcs]p5).
2042 QualType FromTypeCanon = Context.getCanonicalType(FromType);
2043 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2044 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2045 return ICS;
2046
2047 // Check that we have either the same type or a derived type. It
2048 // affects the conversion rank.
2049 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2050 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2051 ICS.Standard.Second = ICK_Identity;
2052 else if (IsDerivedFrom(FromType, ClassType))
2053 ICS.Standard.Second = ICK_Derived_To_Base;
2054 else
2055 return ICS;
2056
2057 // Success. Mark this as a reference binding.
2058 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2059 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2060 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2061 ICS.Standard.ReferenceBinding = true;
2062 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002063 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002064 return ICS;
2065}
2066
2067/// PerformObjectArgumentInitialization - Perform initialization of
2068/// the implicit object parameter for the given Method with the given
2069/// expression.
2070bool
2071Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002072 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002073 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002074 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002075
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002076 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002077 FromRecordType = PT->getPointeeType();
2078 DestType = Method->getThisType(Context);
2079 } else {
2080 FromRecordType = From->getType();
2081 DestType = ImplicitParamRecordType;
2082 }
2083
Mike Stump11289f42009-09-09 15:08:12 +00002084 ImplicitConversionSequence ICS
Douglas Gregor436424c2008-11-18 23:14:02 +00002085 = TryObjectArgumentInitialization(From, Method);
2086 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2087 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002088 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002089 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002090
Douglas Gregor436424c2008-11-18 23:14:02 +00002091 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002092 CheckDerivedToBaseConversion(FromRecordType,
2093 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002094 From->getSourceRange().getBegin(),
2095 From->getSourceRange()))
2096 return true;
2097
Mike Stump11289f42009-09-09 15:08:12 +00002098 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002099 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002100 return false;
2101}
2102
Douglas Gregor5fb53972009-01-14 15:45:31 +00002103/// TryContextuallyConvertToBool - Attempt to contextually convert the
2104/// expression From to bool (C++0x [conv]p3).
2105ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002106 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002107 // FIXME: Are these flags correct?
2108 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002109 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002110 /*ForceRValue=*/false,
2111 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002112}
2113
2114/// PerformContextuallyConvertToBool - Perform a contextual conversion
2115/// of the expression From to bool (C++0x [conv]p3).
2116bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2117 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2118 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2119 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002120
2121 if (!DiagnoseAmbiguousUserDefinedConversion(From, Context.BoolTy))
2122 return Diag(From->getSourceRange().getBegin(),
2123 diag::err_typecheck_bool_condition)
2124 << From->getType() << From->getSourceRange();
2125 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002126}
2127
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002128/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002129/// candidate functions, using the given function call arguments. If
2130/// @p SuppressUserConversions, then don't allow user-defined
2131/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002132/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2133/// hacky way to implement the overloading rules for elidable copy
2134/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002135///
2136/// \para PartialOverloading true if we are performing "partial" overloading
2137/// based on an incomplete set of function arguments. This feature is used by
2138/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002139void
2140Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002141 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002142 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002143 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002144 bool ForceRValue,
2145 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002146 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002147 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002148 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002149 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002150 "Use AddConversionCandidate for conversion functions");
Mike Stump11289f42009-09-09 15:08:12 +00002151 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002152 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002153
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002154 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002155 if (!isa<CXXConstructorDecl>(Method)) {
2156 // If we get here, it's because we're calling a member function
2157 // that is named without a member access expression (e.g.,
2158 // "this->f") that was either written explicitly or created
2159 // implicitly. This can happen with a qualified call to a member
2160 // function, e.g., X::f(). We use a NULL object as the implied
2161 // object argument (C++ [over.call.func]p3).
Mike Stump11289f42009-09-09 15:08:12 +00002162 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002163 SuppressUserConversions, ForceRValue);
2164 return;
2165 }
2166 // We treat a constructor like a non-member function, since its object
2167 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002168 }
2169
2170
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002171 // Add this candidate
2172 CandidateSet.push_back(OverloadCandidate());
2173 OverloadCandidate& Candidate = CandidateSet.back();
2174 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002175 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002176 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002177 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002178
2179 unsigned NumArgsInProto = Proto->getNumArgs();
2180
2181 // (C++ 13.3.2p2): A candidate function having fewer than m
2182 // parameters is viable only if it has an ellipsis in its parameter
2183 // list (8.3.5).
2184 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2185 Candidate.Viable = false;
2186 return;
2187 }
2188
2189 // (C++ 13.3.2p2): A candidate function having more than m parameters
2190 // is viable only if the (m+1)st parameter has a default argument
2191 // (8.3.6). For the purposes of overload resolution, the
2192 // parameter list is truncated on the right, so that there are
2193 // exactly m parameters.
2194 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002195 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002196 // Not enough arguments.
2197 Candidate.Viable = false;
2198 return;
2199 }
2200
2201 // Determine the implicit conversion sequences for each of the
2202 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002203 Candidate.Conversions.resize(NumArgs);
2204 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2205 if (ArgIdx < NumArgsInProto) {
2206 // (C++ 13.3.2p3): for F to be a viable function, there shall
2207 // exist for each argument an implicit conversion sequence
2208 // (13.3.3.1) that converts that argument to the corresponding
2209 // parameter of F.
2210 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002211 Candidate.Conversions[ArgIdx]
2212 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002213 SuppressUserConversions, ForceRValue,
2214 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002215 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002216 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002217 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002218 break;
2219 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002220 } else {
2221 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2222 // argument for which there is no corresponding parameter is
2223 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002224 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002225 = ImplicitConversionSequence::EllipsisConversion;
2226 }
2227 }
2228}
2229
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002230/// \brief Add all of the function declarations in the given function set to
2231/// the overload canddiate set.
2232void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2233 Expr **Args, unsigned NumArgs,
2234 OverloadCandidateSet& CandidateSet,
2235 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002236 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002237 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002238 F != FEnd; ++F) {
2239 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
Mike Stump11289f42009-09-09 15:08:12 +00002240 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002241 SuppressUserConversions);
2242 else
Douglas Gregor89026b52009-06-30 23:57:56 +00002243 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2244 /*FIXME: explicit args */false, 0, 0,
Mike Stump11289f42009-09-09 15:08:12 +00002245 Args, NumArgs, CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002246 SuppressUserConversions);
2247 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002248}
2249
Douglas Gregor436424c2008-11-18 23:14:02 +00002250/// AddMethodCandidate - Adds the given C++ member function to the set
2251/// of candidate functions, using the given function call arguments
2252/// and the object argument (@c Object). For example, in a call
2253/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2254/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2255/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002256/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2257/// a slightly hacky way to implement the overloading rules for elidable copy
2258/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002259void
Douglas Gregor436424c2008-11-18 23:14:02 +00002260Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2261 Expr **Args, unsigned NumArgs,
2262 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002263 bool SuppressUserConversions, bool ForceRValue) {
2264 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002265 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002266 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002267 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor436424c2008-11-18 23:14:02 +00002268 "Use AddConversionCandidate for conversion functions");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002269 assert(!isa<CXXConstructorDecl>(Method) &&
2270 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002271
2272 // Add this candidate
2273 CandidateSet.push_back(OverloadCandidate());
2274 OverloadCandidate& Candidate = CandidateSet.back();
2275 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002276 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002277 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002278
2279 unsigned NumArgsInProto = Proto->getNumArgs();
2280
2281 // (C++ 13.3.2p2): A candidate function having fewer than m
2282 // parameters is viable only if it has an ellipsis in its parameter
2283 // list (8.3.5).
2284 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2285 Candidate.Viable = false;
2286 return;
2287 }
2288
2289 // (C++ 13.3.2p2): A candidate function having more than m parameters
2290 // is viable only if the (m+1)st parameter has a default argument
2291 // (8.3.6). For the purposes of overload resolution, the
2292 // parameter list is truncated on the right, so that there are
2293 // exactly m parameters.
2294 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2295 if (NumArgs < MinRequiredArgs) {
2296 // Not enough arguments.
2297 Candidate.Viable = false;
2298 return;
2299 }
2300
2301 Candidate.Viable = true;
2302 Candidate.Conversions.resize(NumArgs + 1);
2303
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002304 if (Method->isStatic() || !Object)
2305 // The implicit object argument is ignored.
2306 Candidate.IgnoreObjectArgument = true;
2307 else {
2308 // Determine the implicit conversion sequence for the object
2309 // parameter.
2310 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
Mike Stump11289f42009-09-09 15:08:12 +00002311 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002312 == ImplicitConversionSequence::BadConversion) {
2313 Candidate.Viable = false;
2314 return;
2315 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002316 }
2317
2318 // Determine the implicit conversion sequences for each of the
2319 // arguments.
2320 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2321 if (ArgIdx < NumArgsInProto) {
2322 // (C++ 13.3.2p3): for F to be a viable function, there shall
2323 // exist for each argument an implicit conversion sequence
2324 // (13.3.3.1) that converts that argument to the corresponding
2325 // parameter of F.
2326 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002327 Candidate.Conversions[ArgIdx + 1]
2328 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002329 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002330 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002331 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002332 == ImplicitConversionSequence::BadConversion) {
2333 Candidate.Viable = false;
2334 break;
2335 }
2336 } else {
2337 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2338 // argument for which there is no corresponding parameter is
2339 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002340 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002341 = ImplicitConversionSequence::EllipsisConversion;
2342 }
2343 }
2344}
2345
Douglas Gregor97628d62009-08-21 00:16:32 +00002346/// \brief Add a C++ member function template as a candidate to the candidate
2347/// set, using template argument deduction to produce an appropriate member
2348/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002349void
Douglas Gregor97628d62009-08-21 00:16:32 +00002350Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2351 bool HasExplicitTemplateArgs,
2352 const TemplateArgument *ExplicitTemplateArgs,
2353 unsigned NumExplicitTemplateArgs,
2354 Expr *Object, Expr **Args, unsigned NumArgs,
2355 OverloadCandidateSet& CandidateSet,
2356 bool SuppressUserConversions,
2357 bool ForceRValue) {
2358 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002359 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002360 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002361 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002362 // candidate functions in the usual way.113) A given name can refer to one
2363 // or more function templates and also to a set of overloaded non-template
2364 // functions. In such a case, the candidate functions generated from each
2365 // function template are combined with the set of non-template candidate
2366 // functions.
2367 TemplateDeductionInfo Info(Context);
2368 FunctionDecl *Specialization = 0;
2369 if (TemplateDeductionResult Result
2370 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2371 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2372 Args, NumArgs, Specialization, Info)) {
2373 // FIXME: Record what happened with template argument deduction, so
2374 // that we can give the user a beautiful diagnostic.
2375 (void)Result;
2376 return;
2377 }
Mike Stump11289f42009-09-09 15:08:12 +00002378
Douglas Gregor97628d62009-08-21 00:16:32 +00002379 // Add the function template specialization produced by template argument
2380 // deduction as a candidate.
2381 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002382 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002383 "Specialization is not a member function?");
Mike Stump11289f42009-09-09 15:08:12 +00002384 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002385 CandidateSet, SuppressUserConversions, ForceRValue);
2386}
2387
Douglas Gregor05155d82009-08-21 23:19:43 +00002388/// \brief Add a C++ function template specialization as a candidate
2389/// in the candidate set, using template argument deduction to produce
2390/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002391void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002392Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor89026b52009-06-30 23:57:56 +00002393 bool HasExplicitTemplateArgs,
2394 const TemplateArgument *ExplicitTemplateArgs,
2395 unsigned NumExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002396 Expr **Args, unsigned NumArgs,
2397 OverloadCandidateSet& CandidateSet,
2398 bool SuppressUserConversions,
2399 bool ForceRValue) {
2400 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002401 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002402 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002403 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002404 // candidate functions in the usual way.113) A given name can refer to one
2405 // or more function templates and also to a set of overloaded non-template
2406 // functions. In such a case, the candidate functions generated from each
2407 // function template are combined with the set of non-template candidate
2408 // functions.
2409 TemplateDeductionInfo Info(Context);
2410 FunctionDecl *Specialization = 0;
2411 if (TemplateDeductionResult Result
Douglas Gregor89026b52009-06-30 23:57:56 +00002412 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2413 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2414 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002415 // FIXME: Record what happened with template argument deduction, so
2416 // that we can give the user a beautiful diagnostic.
2417 (void)Result;
2418 return;
2419 }
Mike Stump11289f42009-09-09 15:08:12 +00002420
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002421 // Add the function template specialization produced by template argument
2422 // deduction as a candidate.
2423 assert(Specialization && "Missing function template specialization?");
2424 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2425 SuppressUserConversions, ForceRValue);
2426}
Mike Stump11289f42009-09-09 15:08:12 +00002427
Douglas Gregora1f013e2008-11-07 22:36:19 +00002428/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002429/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002430/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002431/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002432/// (which may or may not be the same type as the type that the
2433/// conversion function produces).
2434void
2435Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2436 Expr *From, QualType ToType,
2437 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002438 assert(!Conversion->getDescribedFunctionTemplate() &&
2439 "Conversion function templates use AddTemplateConversionCandidate");
2440
Douglas Gregora1f013e2008-11-07 22:36:19 +00002441 // Add this candidate
2442 CandidateSet.push_back(OverloadCandidate());
2443 OverloadCandidate& Candidate = CandidateSet.back();
2444 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002445 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002446 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002447 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00002448 Candidate.FinalConversion.FromTypePtr
Douglas Gregora1f013e2008-11-07 22:36:19 +00002449 = Conversion->getConversionType().getAsOpaquePtr();
2450 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2451
Douglas Gregor436424c2008-11-18 23:14:02 +00002452 // Determine the implicit conversion sequence for the implicit
2453 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002454 Candidate.Viable = true;
2455 Candidate.Conversions.resize(1);
Douglas Gregor436424c2008-11-18 23:14:02 +00002456 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002457 // Conversion functions to a different type in the base class is visible in
2458 // the derived class. So, a derived to base conversion should not participate
2459 // in overload resolution.
2460 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2461 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump11289f42009-09-09 15:08:12 +00002462 if (Candidate.Conversions[0].ConversionKind
Douglas Gregora1f013e2008-11-07 22:36:19 +00002463 == ImplicitConversionSequence::BadConversion) {
2464 Candidate.Viable = false;
2465 return;
2466 }
2467
2468 // To determine what the conversion from the result of calling the
2469 // conversion function to the type we're eventually trying to
2470 // convert to (ToType), we need to synthesize a call to the
2471 // conversion function and attempt copy initialization from it. This
2472 // makes sure that we get the right semantics with respect to
2473 // lvalues/rvalues and the type. Fortunately, we can allocate this
2474 // call on the stack and we don't need its arguments to be
2475 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002476 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregora1f013e2008-11-07 22:36:19 +00002477 SourceLocation());
2478 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Anders Carlssona2615922009-07-31 00:48:10 +00002479 CastExpr::CK_Unknown,
Douglas Gregora11693b2008-11-12 17:17:38 +00002480 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002481
2482 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002483 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2484 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002485 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002486 Conversion->getConversionType().getNonReferenceType(),
2487 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002488 ImplicitConversionSequence ICS =
2489 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002490 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002491 /*ForceRValue=*/false,
2492 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002493
Douglas Gregora1f013e2008-11-07 22:36:19 +00002494 switch (ICS.ConversionKind) {
2495 case ImplicitConversionSequence::StandardConversion:
2496 Candidate.FinalConversion = ICS.Standard;
2497 break;
2498
2499 case ImplicitConversionSequence::BadConversion:
2500 Candidate.Viable = false;
2501 break;
2502
2503 default:
Mike Stump11289f42009-09-09 15:08:12 +00002504 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002505 "Can only end up with a standard conversion sequence or failure");
2506 }
2507}
2508
Douglas Gregor05155d82009-08-21 23:19:43 +00002509/// \brief Adds a conversion function template specialization
2510/// candidate to the overload set, using template argument deduction
2511/// to deduce the template arguments of the conversion function
2512/// template from the type that we are converting to (C++
2513/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002514void
Douglas Gregor05155d82009-08-21 23:19:43 +00002515Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2516 Expr *From, QualType ToType,
2517 OverloadCandidateSet &CandidateSet) {
2518 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2519 "Only conversion function templates permitted here");
2520
2521 TemplateDeductionInfo Info(Context);
2522 CXXConversionDecl *Specialization = 0;
2523 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002524 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002525 Specialization, Info)) {
2526 // FIXME: Record what happened with template argument deduction, so
2527 // that we can give the user a beautiful diagnostic.
2528 (void)Result;
2529 return;
2530 }
Mike Stump11289f42009-09-09 15:08:12 +00002531
Douglas Gregor05155d82009-08-21 23:19:43 +00002532 // Add the conversion function template specialization produced by
2533 // template argument deduction as a candidate.
2534 assert(Specialization && "Missing function template specialization?");
2535 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2536}
2537
Douglas Gregorab7897a2008-11-19 22:57:39 +00002538/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2539/// converts the given @c Object to a function pointer via the
2540/// conversion function @c Conversion, and then attempts to call it
2541/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2542/// the type of function that we'll eventually be calling.
2543void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002544 const FunctionProtoType *Proto,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002545 Expr *Object, Expr **Args, unsigned NumArgs,
2546 OverloadCandidateSet& CandidateSet) {
2547 CandidateSet.push_back(OverloadCandidate());
2548 OverloadCandidate& Candidate = CandidateSet.back();
2549 Candidate.Function = 0;
2550 Candidate.Surrogate = Conversion;
2551 Candidate.Viable = true;
2552 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002553 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002554 Candidate.Conversions.resize(NumArgs + 1);
2555
2556 // Determine the implicit conversion sequence for the implicit
2557 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002558 ImplicitConversionSequence ObjectInit
Douglas Gregorab7897a2008-11-19 22:57:39 +00002559 = TryObjectArgumentInitialization(Object, Conversion);
2560 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2561 Candidate.Viable = false;
2562 return;
2563 }
2564
2565 // The first conversion is actually a user-defined conversion whose
2566 // first conversion is ObjectInit's standard conversion (which is
2567 // effectively a reference binding). Record it as such.
Mike Stump11289f42009-09-09 15:08:12 +00002568 Candidate.Conversions[0].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002569 = ImplicitConversionSequence::UserDefinedConversion;
2570 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2571 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002572 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002573 = Candidate.Conversions[0].UserDefined.Before;
2574 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2575
Mike Stump11289f42009-09-09 15:08:12 +00002576 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002577 unsigned NumArgsInProto = Proto->getNumArgs();
2578
2579 // (C++ 13.3.2p2): A candidate function having fewer than m
2580 // parameters is viable only if it has an ellipsis in its parameter
2581 // list (8.3.5).
2582 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2583 Candidate.Viable = false;
2584 return;
2585 }
2586
2587 // Function types don't have any default arguments, so just check if
2588 // we have enough arguments.
2589 if (NumArgs < NumArgsInProto) {
2590 // Not enough arguments.
2591 Candidate.Viable = false;
2592 return;
2593 }
2594
2595 // Determine the implicit conversion sequences for each of the
2596 // arguments.
2597 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2598 if (ArgIdx < NumArgsInProto) {
2599 // (C++ 13.3.2p3): for F to be a viable function, there shall
2600 // exist for each argument an implicit conversion sequence
2601 // (13.3.3.1) that converts that argument to the corresponding
2602 // parameter of F.
2603 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002604 Candidate.Conversions[ArgIdx + 1]
2605 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002606 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002607 /*ForceRValue=*/false,
2608 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002609 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002610 == ImplicitConversionSequence::BadConversion) {
2611 Candidate.Viable = false;
2612 break;
2613 }
2614 } else {
2615 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2616 // argument for which there is no corresponding parameter is
2617 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002618 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002619 = ImplicitConversionSequence::EllipsisConversion;
2620 }
2621 }
2622}
2623
Mike Stump87c57ac2009-05-16 07:39:55 +00002624// FIXME: This will eventually be removed, once we've migrated all of the
2625// operator overloading logic over to the scheme used by binary operators, which
2626// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002627void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002628 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002629 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002630 OverloadCandidateSet& CandidateSet,
2631 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002632
2633 FunctionSet Functions;
2634
2635 QualType T1 = Args[0]->getType();
2636 QualType T2;
2637 if (NumArgs > 1)
2638 T2 = Args[1]->getType();
2639
2640 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002641 if (S)
2642 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002643 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2644 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2645 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2646 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2647}
2648
2649/// \brief Add overload candidates for overloaded operators that are
2650/// member functions.
2651///
2652/// Add the overloaded operator candidates that are member functions
2653/// for the operator Op that was used in an operator expression such
2654/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2655/// CandidateSet will store the added overload candidates. (C++
2656/// [over.match.oper]).
2657void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2658 SourceLocation OpLoc,
2659 Expr **Args, unsigned NumArgs,
2660 OverloadCandidateSet& CandidateSet,
2661 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002662 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2663
2664 // C++ [over.match.oper]p3:
2665 // For a unary operator @ with an operand of a type whose
2666 // cv-unqualified version is T1, and for a binary operator @ with
2667 // a left operand of a type whose cv-unqualified version is T1 and
2668 // a right operand of a type whose cv-unqualified version is T2,
2669 // three sets of candidate functions, designated member
2670 // candidates, non-member candidates and built-in candidates, are
2671 // constructed as follows:
2672 QualType T1 = Args[0]->getType();
2673 QualType T2;
2674 if (NumArgs > 1)
2675 T2 = Args[1]->getType();
2676
2677 // -- If T1 is a class type, the set of member candidates is the
2678 // result of the qualified lookup of T1::operator@
2679 // (13.3.1.1.1); otherwise, the set of member candidates is
2680 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002681 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002682 // Complete the type if it can be completed. Otherwise, we're done.
2683 if (RequireCompleteType(OpLoc, T1, PartialDiagnostic(0)))
2684 return;
Mike Stump11289f42009-09-09 15:08:12 +00002685
2686 LookupResult Operators = LookupQualifiedName(T1Rec->getDecl(), OpName,
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002687 LookupOrdinaryName, false);
Mike Stump11289f42009-09-09 15:08:12 +00002688 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002689 OperEnd = Operators.end();
2690 Oper != OperEnd;
2691 ++Oper)
Mike Stump11289f42009-09-09 15:08:12 +00002692 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
Douglas Gregor55297ac2008-12-23 00:26:44 +00002693 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor436424c2008-11-18 23:14:02 +00002694 /*SuppressUserConversions=*/false);
Douglas Gregor436424c2008-11-18 23:14:02 +00002695 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002696}
2697
Douglas Gregora11693b2008-11-12 17:17:38 +00002698/// AddBuiltinCandidate - Add a candidate for a built-in
2699/// operator. ResultTy and ParamTys are the result and parameter types
2700/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00002701/// arguments being passed to the candidate. IsAssignmentOperator
2702/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00002703/// operator. NumContextualBoolArguments is the number of arguments
2704/// (at the beginning of the argument list) that will be contextually
2705/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00002706void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00002707 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00002708 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002709 bool IsAssignmentOperator,
2710 unsigned NumContextualBoolArguments) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002711 // Add this candidate
2712 CandidateSet.push_back(OverloadCandidate());
2713 OverloadCandidate& Candidate = CandidateSet.back();
2714 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00002715 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002716 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00002717 Candidate.BuiltinTypes.ResultTy = ResultTy;
2718 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2719 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2720
2721 // Determine the implicit conversion sequences for each of the
2722 // arguments.
2723 Candidate.Viable = true;
2724 Candidate.Conversions.resize(NumArgs);
2725 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00002726 // C++ [over.match.oper]p4:
2727 // For the built-in assignment operators, conversions of the
2728 // left operand are restricted as follows:
2729 // -- no temporaries are introduced to hold the left operand, and
2730 // -- no user-defined conversions are applied to the left
2731 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00002732 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00002733 //
2734 // We block these conversions by turning off user-defined
2735 // conversions, since that is the only way that initialization of
2736 // a reference to a non-class type can occur from something that
2737 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002738 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00002739 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00002740 "Contextual conversion to bool requires bool type");
2741 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2742 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002743 Candidate.Conversions[ArgIdx]
2744 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00002745 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00002746 /*ForceRValue=*/false,
2747 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002748 }
Mike Stump11289f42009-09-09 15:08:12 +00002749 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002750 == ImplicitConversionSequence::BadConversion) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002751 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002752 break;
2753 }
Douglas Gregora11693b2008-11-12 17:17:38 +00002754 }
2755}
2756
2757/// BuiltinCandidateTypeSet - A set of types that will be used for the
2758/// candidate operator functions for built-in operators (C++
2759/// [over.built]). The types are separated into pointer types and
2760/// enumeration types.
2761class BuiltinCandidateTypeSet {
2762 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002763 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00002764
2765 /// PointerTypes - The set of pointer types that will be used in the
2766 /// built-in candidates.
2767 TypeSet PointerTypes;
2768
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002769 /// MemberPointerTypes - The set of member pointer types that will be
2770 /// used in the built-in candidates.
2771 TypeSet MemberPointerTypes;
2772
Douglas Gregora11693b2008-11-12 17:17:38 +00002773 /// EnumerationTypes - The set of enumeration types that will be
2774 /// used in the built-in candidates.
2775 TypeSet EnumerationTypes;
2776
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002777 /// Sema - The semantic analysis instance where we are building the
2778 /// candidate type set.
2779 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00002780
Douglas Gregora11693b2008-11-12 17:17:38 +00002781 /// Context - The AST context in which we will build the type sets.
2782 ASTContext &Context;
2783
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002784 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2785 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002786
2787public:
2788 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002789 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00002790
Mike Stump11289f42009-09-09 15:08:12 +00002791 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002792 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00002793
Douglas Gregor5fb53972009-01-14 15:45:31 +00002794 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2795 bool AllowExplicitConversions);
Douglas Gregora11693b2008-11-12 17:17:38 +00002796
2797 /// pointer_begin - First pointer type found;
2798 iterator pointer_begin() { return PointerTypes.begin(); }
2799
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002800 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002801 iterator pointer_end() { return PointerTypes.end(); }
2802
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002803 /// member_pointer_begin - First member pointer type found;
2804 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2805
2806 /// member_pointer_end - Past the last member pointer type found;
2807 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2808
Douglas Gregora11693b2008-11-12 17:17:38 +00002809 /// enumeration_begin - First enumeration type found;
2810 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2811
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002812 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002813 iterator enumeration_end() { return EnumerationTypes.end(); }
2814};
2815
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002816/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00002817/// the set of pointer types along with any more-qualified variants of
2818/// that type. For example, if @p Ty is "int const *", this routine
2819/// will add "int const *", "int const volatile *", "int const
2820/// restrict *", and "int const volatile restrict *" to the set of
2821/// pointer types. Returns true if the add of @p Ty itself succeeded,
2822/// false otherwise.
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002823bool
2824BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002825 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002826 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00002827 return false;
2828
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002829 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002830 QualType PointeeTy = PointerTy->getPointeeType();
2831 // FIXME: Optimize this so that we don't keep trying to add the same types.
2832
Mike Stump87c57ac2009-05-16 07:39:55 +00002833 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2834 // pointer conversions that don't cast away constness?
Douglas Gregora11693b2008-11-12 17:17:38 +00002835 if (!PointeeTy.isConstQualified())
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002836 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregora11693b2008-11-12 17:17:38 +00002837 (Context.getPointerType(PointeeTy.withConst()));
2838 if (!PointeeTy.isVolatileQualified())
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002839 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregora11693b2008-11-12 17:17:38 +00002840 (Context.getPointerType(PointeeTy.withVolatile()));
2841 if (!PointeeTy.isRestrictQualified())
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002842 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregora11693b2008-11-12 17:17:38 +00002843 (Context.getPointerType(PointeeTy.withRestrict()));
2844 }
2845
2846 return true;
2847}
2848
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002849/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2850/// to the set of pointer types along with any more-qualified variants of
2851/// that type. For example, if @p Ty is "int const *", this routine
2852/// will add "int const *", "int const volatile *", "int const
2853/// restrict *", and "int const volatile restrict *" to the set of
2854/// pointer types. Returns true if the add of @p Ty itself succeeded,
2855/// false otherwise.
2856bool
2857BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2858 QualType Ty) {
2859 // Insert this type.
2860 if (!MemberPointerTypes.insert(Ty))
2861 return false;
2862
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002863 if (const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>()) {
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002864 QualType PointeeTy = PointerTy->getPointeeType();
2865 const Type *ClassTy = PointerTy->getClass();
2866 // FIXME: Optimize this so that we don't keep trying to add the same types.
2867
2868 if (!PointeeTy.isConstQualified())
2869 AddMemberPointerWithMoreQualifiedTypeVariants
2870 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2871 if (!PointeeTy.isVolatileQualified())
2872 AddMemberPointerWithMoreQualifiedTypeVariants
2873 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2874 if (!PointeeTy.isRestrictQualified())
2875 AddMemberPointerWithMoreQualifiedTypeVariants
2876 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2877 }
2878
2879 return true;
2880}
2881
Douglas Gregora11693b2008-11-12 17:17:38 +00002882/// AddTypesConvertedFrom - Add each of the types to which the type @p
2883/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002884/// primarily interested in pointer types and enumeration types. We also
2885/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002886/// AllowUserConversions is true if we should look at the conversion
2887/// functions of a class type, and AllowExplicitConversions if we
2888/// should also include the explicit conversion functions of a class
2889/// type.
Mike Stump11289f42009-09-09 15:08:12 +00002890void
Douglas Gregor5fb53972009-01-14 15:45:31 +00002891BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2892 bool AllowUserConversions,
2893 bool AllowExplicitConversions) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002894 // Only deal with canonical types.
2895 Ty = Context.getCanonicalType(Ty);
2896
2897 // Look through reference types; they aren't part of the type of an
2898 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002899 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00002900 Ty = RefTy->getPointeeType();
2901
2902 // We don't care about qualifiers on the type.
2903 Ty = Ty.getUnqualifiedType();
2904
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002905 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002906 QualType PointeeTy = PointerTy->getPointeeType();
2907
2908 // Insert our type, and its more-qualified variants, into the set
2909 // of types.
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002910 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00002911 return;
2912
2913 // Add 'cv void*' to our set of types.
2914 if (!Ty->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002915 QualType QualVoid
Douglas Gregora11693b2008-11-12 17:17:38 +00002916 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002917 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregora11693b2008-11-12 17:17:38 +00002918 }
2919
2920 // If this is a pointer to a class type, add pointers to its bases
2921 // (with the same level of cv-qualification as the original
2922 // derived class, of course).
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002923 if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002924 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2925 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2926 Base != ClassDecl->bases_end(); ++Base) {
2927 QualType BaseTy = Context.getCanonicalType(Base->getType());
2928 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2929
2930 // Add the pointer type, recursively, so that we get all of
2931 // the indirect base classes, too.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002932 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregora11693b2008-11-12 17:17:38 +00002933 }
2934 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002935 } else if (Ty->isMemberPointerType()) {
2936 // Member pointers are far easier, since the pointee can't be converted.
2937 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2938 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00002939 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00002940 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002941 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002942 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002943 if (SemaRef.RequireCompleteType(SourceLocation(), Ty, 0)) {
2944 // No conversion functions in incomplete types.
2945 return;
2946 }
Mike Stump11289f42009-09-09 15:08:12 +00002947
Douglas Gregora11693b2008-11-12 17:17:38 +00002948 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2949 // FIXME: Visit conversion functions in the base classes, too.
Mike Stump11289f42009-09-09 15:08:12 +00002950 OverloadedFunctionDecl *Conversions
Douglas Gregora11693b2008-11-12 17:17:38 +00002951 = ClassDecl->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00002952 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregora11693b2008-11-12 17:17:38 +00002953 = Conversions->function_begin();
2954 Func != Conversions->function_end(); ++Func) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002955 CXXConversionDecl *Conv;
2956 FunctionTemplateDecl *ConvTemplate;
2957 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
2958
Mike Stump11289f42009-09-09 15:08:12 +00002959 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00002960 // about which builtin types we can convert to.
2961 if (ConvTemplate)
2962 continue;
2963
Douglas Gregor5fb53972009-01-14 15:45:31 +00002964 if (AllowExplicitConversions || !Conv->isExplicit())
2965 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregora11693b2008-11-12 17:17:38 +00002966 }
2967 }
2968 }
2969}
2970
Douglas Gregor84605ae2009-08-24 13:43:27 +00002971/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
2972/// the volatile- and non-volatile-qualified assignment operators for the
2973/// given type to the candidate set.
2974static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
2975 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00002976 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00002977 unsigned NumArgs,
2978 OverloadCandidateSet &CandidateSet) {
2979 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002980
Douglas Gregor84605ae2009-08-24 13:43:27 +00002981 // T& operator=(T&, T)
2982 ParamTypes[0] = S.Context.getLValueReferenceType(T);
2983 ParamTypes[1] = T;
2984 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2985 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002986
Douglas Gregor84605ae2009-08-24 13:43:27 +00002987 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
2988 // volatile T& operator=(volatile T&, T)
2989 ParamTypes[0] = S.Context.getLValueReferenceType(T.withVolatile());
2990 ParamTypes[1] = T;
2991 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002992 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00002993 }
2994}
Mike Stump11289f42009-09-09 15:08:12 +00002995
Douglas Gregord08452f2008-11-19 15:42:04 +00002996/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2997/// operator overloads to the candidate set (C++ [over.built]), based
2998/// on the operator @p Op and the arguments given. For example, if the
2999/// operator is a binary '+', this routine might add "int
3000/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003001void
Mike Stump11289f42009-09-09 15:08:12 +00003002Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregord08452f2008-11-19 15:42:04 +00003003 Expr **Args, unsigned NumArgs,
3004 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003005 // The set of "promoted arithmetic types", which are the arithmetic
3006 // types are that preserved by promotion (C++ [over.built]p2). Note
3007 // that the first few of these types are the promoted integral
3008 // types; these types need to be first.
3009 // FIXME: What about complex?
3010 const unsigned FirstIntegralType = 0;
3011 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003012 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003013 LastPromotedIntegralType = 13;
3014 const unsigned FirstPromotedArithmeticType = 7,
3015 LastPromotedArithmeticType = 16;
3016 const unsigned NumArithmeticTypes = 16;
3017 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003018 Context.BoolTy, Context.CharTy, Context.WCharTy,
3019// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003020 Context.SignedCharTy, Context.ShortTy,
3021 Context.UnsignedCharTy, Context.UnsignedShortTy,
3022 Context.IntTy, Context.LongTy, Context.LongLongTy,
3023 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3024 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3025 };
3026
3027 // Find all of the types that the arguments can convert to, but only
3028 // if the operator we're looking at has built-in operator candidates
3029 // that make use of these types.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003030 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003031 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3032 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003033 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003034 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003035 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003036 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003037 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003038 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3039 true,
3040 (Op == OO_Exclaim ||
3041 Op == OO_AmpAmp ||
3042 Op == OO_PipePipe));
Douglas Gregora11693b2008-11-12 17:17:38 +00003043 }
3044
3045 bool isComparison = false;
3046 switch (Op) {
3047 case OO_None:
3048 case NUM_OVERLOADED_OPERATORS:
3049 assert(false && "Expected an overloaded operator");
3050 break;
3051
Douglas Gregord08452f2008-11-19 15:42:04 +00003052 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003053 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003054 goto UnaryStar;
3055 else
3056 goto BinaryStar;
3057 break;
3058
3059 case OO_Plus: // '+' is either unary or binary
3060 if (NumArgs == 1)
3061 goto UnaryPlus;
3062 else
3063 goto BinaryPlus;
3064 break;
3065
3066 case OO_Minus: // '-' is either unary or binary
3067 if (NumArgs == 1)
3068 goto UnaryMinus;
3069 else
3070 goto BinaryMinus;
3071 break;
3072
3073 case OO_Amp: // '&' is either unary or binary
3074 if (NumArgs == 1)
3075 goto UnaryAmp;
3076 else
3077 goto BinaryAmp;
3078
3079 case OO_PlusPlus:
3080 case OO_MinusMinus:
3081 // C++ [over.built]p3:
3082 //
3083 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3084 // is either volatile or empty, there exist candidate operator
3085 // functions of the form
3086 //
3087 // VQ T& operator++(VQ T&);
3088 // T operator++(VQ T&, int);
3089 //
3090 // C++ [over.built]p4:
3091 //
3092 // For every pair (T, VQ), where T is an arithmetic type other
3093 // than bool, and VQ is either volatile or empty, there exist
3094 // candidate operator functions of the form
3095 //
3096 // VQ T& operator--(VQ T&);
3097 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003098 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003099 Arith < NumArithmeticTypes; ++Arith) {
3100 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003101 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003102 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003103
3104 // Non-volatile version.
3105 if (NumArgs == 1)
3106 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3107 else
3108 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3109
3110 // Volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003111 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregord08452f2008-11-19 15:42:04 +00003112 if (NumArgs == 1)
3113 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3114 else
3115 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3116 }
3117
3118 // C++ [over.built]p5:
3119 //
3120 // For every pair (T, VQ), where T is a cv-qualified or
3121 // cv-unqualified object type, and VQ is either volatile or
3122 // empty, there exist candidate operator functions of the form
3123 //
3124 // T*VQ& operator++(T*VQ&);
3125 // T*VQ& operator--(T*VQ&);
3126 // T* operator++(T*VQ&, int);
3127 // T* operator--(T*VQ&, int);
3128 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3129 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3130 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003131 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003132 continue;
3133
Mike Stump11289f42009-09-09 15:08:12 +00003134 QualType ParamTypes[2] = {
3135 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003136 };
Mike Stump11289f42009-09-09 15:08:12 +00003137
Douglas Gregord08452f2008-11-19 15:42:04 +00003138 // Without volatile
3139 if (NumArgs == 1)
3140 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3141 else
3142 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3143
3144 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3145 // With volatile
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003146 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregord08452f2008-11-19 15:42:04 +00003147 if (NumArgs == 1)
3148 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3149 else
3150 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3151 }
3152 }
3153 break;
3154
3155 UnaryStar:
3156 // C++ [over.built]p6:
3157 // For every cv-qualified or cv-unqualified object type T, there
3158 // exist candidate operator functions of the form
3159 //
3160 // T& operator*(T*);
3161 //
3162 // C++ [over.built]p7:
3163 // For every function type T, there exist candidate operator
3164 // functions of the form
3165 // T& operator*(T*);
3166 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3167 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3168 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003169 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003170 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003171 &ParamTy, Args, 1, CandidateSet);
3172 }
3173 break;
3174
3175 UnaryPlus:
3176 // C++ [over.built]p8:
3177 // For every type T, there exist candidate operator functions of
3178 // the form
3179 //
3180 // T* operator+(T*);
3181 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3182 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3183 QualType ParamTy = *Ptr;
3184 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3185 }
Mike Stump11289f42009-09-09 15:08:12 +00003186
Douglas Gregord08452f2008-11-19 15:42:04 +00003187 // Fall through
3188
3189 UnaryMinus:
3190 // C++ [over.built]p9:
3191 // For every promoted arithmetic type T, there exist candidate
3192 // operator functions of the form
3193 //
3194 // T operator+(T);
3195 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003196 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003197 Arith < LastPromotedArithmeticType; ++Arith) {
3198 QualType ArithTy = ArithmeticTypes[Arith];
3199 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3200 }
3201 break;
3202
3203 case OO_Tilde:
3204 // C++ [over.built]p10:
3205 // For every promoted integral type T, there exist candidate
3206 // operator functions of the form
3207 //
3208 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003209 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003210 Int < LastPromotedIntegralType; ++Int) {
3211 QualType IntTy = ArithmeticTypes[Int];
3212 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3213 }
3214 break;
3215
Douglas Gregora11693b2008-11-12 17:17:38 +00003216 case OO_New:
3217 case OO_Delete:
3218 case OO_Array_New:
3219 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003220 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003221 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003222 break;
3223
3224 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003225 UnaryAmp:
3226 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003227 // C++ [over.match.oper]p3:
3228 // -- For the operator ',', the unary operator '&', or the
3229 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003230 break;
3231
Douglas Gregor84605ae2009-08-24 13:43:27 +00003232 case OO_EqualEqual:
3233 case OO_ExclaimEqual:
3234 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003235 // For every pointer to member type T, there exist candidate operator
3236 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003237 //
3238 // bool operator==(T,T);
3239 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003240 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003241 MemPtr = CandidateTypes.member_pointer_begin(),
3242 MemPtrEnd = CandidateTypes.member_pointer_end();
3243 MemPtr != MemPtrEnd;
3244 ++MemPtr) {
3245 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3246 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3247 }
Mike Stump11289f42009-09-09 15:08:12 +00003248
Douglas Gregor84605ae2009-08-24 13:43:27 +00003249 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003250
Douglas Gregora11693b2008-11-12 17:17:38 +00003251 case OO_Less:
3252 case OO_Greater:
3253 case OO_LessEqual:
3254 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003255 // C++ [over.built]p15:
3256 //
3257 // For every pointer or enumeration type T, there exist
3258 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003259 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003260 // bool operator<(T, T);
3261 // bool operator>(T, T);
3262 // bool operator<=(T, T);
3263 // bool operator>=(T, T);
3264 // bool operator==(T, T);
3265 // bool operator!=(T, T);
3266 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3267 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3268 QualType ParamTypes[2] = { *Ptr, *Ptr };
3269 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3270 }
Mike Stump11289f42009-09-09 15:08:12 +00003271 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003272 = CandidateTypes.enumeration_begin();
3273 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3274 QualType ParamTypes[2] = { *Enum, *Enum };
3275 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3276 }
3277
3278 // Fall through.
3279 isComparison = true;
3280
Douglas Gregord08452f2008-11-19 15:42:04 +00003281 BinaryPlus:
3282 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003283 if (!isComparison) {
3284 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3285
3286 // C++ [over.built]p13:
3287 //
3288 // For every cv-qualified or cv-unqualified object type T
3289 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003290 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003291 // T* operator+(T*, ptrdiff_t);
3292 // T& operator[](T*, ptrdiff_t); [BELOW]
3293 // T* operator-(T*, ptrdiff_t);
3294 // T* operator+(ptrdiff_t, T*);
3295 // T& operator[](ptrdiff_t, T*); [BELOW]
3296 //
3297 // C++ [over.built]p14:
3298 //
3299 // For every T, where T is a pointer to object type, there
3300 // exist candidate operator functions of the form
3301 //
3302 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003303 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003304 = CandidateTypes.pointer_begin();
3305 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3306 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3307
3308 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3309 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3310
3311 if (Op == OO_Plus) {
3312 // T* operator+(ptrdiff_t, T*);
3313 ParamTypes[0] = ParamTypes[1];
3314 ParamTypes[1] = *Ptr;
3315 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3316 } else {
3317 // ptrdiff_t operator-(T, T);
3318 ParamTypes[1] = *Ptr;
3319 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3320 Args, 2, CandidateSet);
3321 }
3322 }
3323 }
3324 // Fall through
3325
Douglas Gregora11693b2008-11-12 17:17:38 +00003326 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003327 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003328 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003329 // C++ [over.built]p12:
3330 //
3331 // For every pair of promoted arithmetic types L and R, there
3332 // exist candidate operator functions of the form
3333 //
3334 // LR operator*(L, R);
3335 // LR operator/(L, R);
3336 // LR operator+(L, R);
3337 // LR operator-(L, R);
3338 // bool operator<(L, R);
3339 // bool operator>(L, R);
3340 // bool operator<=(L, R);
3341 // bool operator>=(L, R);
3342 // bool operator==(L, R);
3343 // bool operator!=(L, R);
3344 //
3345 // where LR is the result of the usual arithmetic conversions
3346 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003347 //
3348 // C++ [over.built]p24:
3349 //
3350 // For every pair of promoted arithmetic types L and R, there exist
3351 // candidate operator functions of the form
3352 //
3353 // LR operator?(bool, L, R);
3354 //
3355 // where LR is the result of the usual arithmetic conversions
3356 // between types L and R.
3357 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003358 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003359 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003360 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003361 Right < LastPromotedArithmeticType; ++Right) {
3362 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003363 QualType Result
3364 = isComparison
3365 ? Context.BoolTy
3366 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003367 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3368 }
3369 }
3370 break;
3371
3372 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003373 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003374 case OO_Caret:
3375 case OO_Pipe:
3376 case OO_LessLess:
3377 case OO_GreaterGreater:
3378 // C++ [over.built]p17:
3379 //
3380 // For every pair of promoted integral types L and R, there
3381 // exist candidate operator functions of the form
3382 //
3383 // LR operator%(L, R);
3384 // LR operator&(L, R);
3385 // LR operator^(L, R);
3386 // LR operator|(L, R);
3387 // L operator<<(L, R);
3388 // L operator>>(L, R);
3389 //
3390 // where LR is the result of the usual arithmetic conversions
3391 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003392 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003393 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003394 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003395 Right < LastPromotedIntegralType; ++Right) {
3396 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3397 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3398 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003399 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003400 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3401 }
3402 }
3403 break;
3404
3405 case OO_Equal:
3406 // C++ [over.built]p20:
3407 //
3408 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003409 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003410 // empty, there exist candidate operator functions of the form
3411 //
3412 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003413 for (BuiltinCandidateTypeSet::iterator
3414 Enum = CandidateTypes.enumeration_begin(),
3415 EnumEnd = CandidateTypes.enumeration_end();
3416 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003417 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003418 CandidateSet);
3419 for (BuiltinCandidateTypeSet::iterator
3420 MemPtr = CandidateTypes.member_pointer_begin(),
3421 MemPtrEnd = CandidateTypes.member_pointer_end();
3422 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003423 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003424 CandidateSet);
3425 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003426
3427 case OO_PlusEqual:
3428 case OO_MinusEqual:
3429 // C++ [over.built]p19:
3430 //
3431 // For every pair (T, VQ), where T is any type and VQ is either
3432 // volatile or empty, there exist candidate operator functions
3433 // of the form
3434 //
3435 // T*VQ& operator=(T*VQ&, T*);
3436 //
3437 // C++ [over.built]p21:
3438 //
3439 // For every pair (T, VQ), where T is a cv-qualified or
3440 // cv-unqualified object type and VQ is either volatile or
3441 // empty, there exist candidate operator functions of the form
3442 //
3443 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3444 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3445 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3446 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3447 QualType ParamTypes[2];
3448 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3449
3450 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003451 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003452 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3453 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003454
Douglas Gregord08452f2008-11-19 15:42:04 +00003455 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3456 // volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003457 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregorc5e61072009-01-13 00:52:54 +00003458 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3459 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003460 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003461 }
3462 // Fall through.
3463
3464 case OO_StarEqual:
3465 case OO_SlashEqual:
3466 // C++ [over.built]p18:
3467 //
3468 // For every triple (L, VQ, R), where L is an arithmetic type,
3469 // VQ is either volatile or empty, and R is a promoted
3470 // arithmetic type, there exist candidate operator functions of
3471 // the form
3472 //
3473 // VQ L& operator=(VQ L&, R);
3474 // VQ L& operator*=(VQ L&, R);
3475 // VQ L& operator/=(VQ L&, R);
3476 // VQ L& operator+=(VQ L&, R);
3477 // VQ L& operator-=(VQ L&, R);
3478 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003479 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003480 Right < LastPromotedArithmeticType; ++Right) {
3481 QualType ParamTypes[2];
3482 ParamTypes[1] = ArithmeticTypes[Right];
3483
3484 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003485 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003486 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3487 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003488
3489 // Add this built-in operator as a candidate (VQ is 'volatile').
3490 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003491 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003492 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3493 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003494 }
3495 }
3496 break;
3497
3498 case OO_PercentEqual:
3499 case OO_LessLessEqual:
3500 case OO_GreaterGreaterEqual:
3501 case OO_AmpEqual:
3502 case OO_CaretEqual:
3503 case OO_PipeEqual:
3504 // C++ [over.built]p22:
3505 //
3506 // For every triple (L, VQ, R), where L is an integral type, VQ
3507 // is either volatile or empty, and R is a promoted integral
3508 // type, there exist candidate operator functions of the form
3509 //
3510 // VQ L& operator%=(VQ L&, R);
3511 // VQ L& operator<<=(VQ L&, R);
3512 // VQ L& operator>>=(VQ L&, R);
3513 // VQ L& operator&=(VQ L&, R);
3514 // VQ L& operator^=(VQ L&, R);
3515 // VQ L& operator|=(VQ L&, R);
3516 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003517 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003518 Right < LastPromotedIntegralType; ++Right) {
3519 QualType ParamTypes[2];
3520 ParamTypes[1] = ArithmeticTypes[Right];
3521
3522 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003523 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003524 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3525
3526 // Add this built-in operator as a candidate (VQ is 'volatile').
3527 ParamTypes[0] = ArithmeticTypes[Left];
3528 ParamTypes[0].addVolatile();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003529 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003530 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3531 }
3532 }
3533 break;
3534
Douglas Gregord08452f2008-11-19 15:42:04 +00003535 case OO_Exclaim: {
3536 // C++ [over.operator]p23:
3537 //
3538 // There also exist candidate operator functions of the form
3539 //
Mike Stump11289f42009-09-09 15:08:12 +00003540 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003541 // bool operator&&(bool, bool); [BELOW]
3542 // bool operator||(bool, bool); [BELOW]
3543 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003544 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3545 /*IsAssignmentOperator=*/false,
3546 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003547 break;
3548 }
3549
Douglas Gregora11693b2008-11-12 17:17:38 +00003550 case OO_AmpAmp:
3551 case OO_PipePipe: {
3552 // C++ [over.operator]p23:
3553 //
3554 // There also exist candidate operator functions of the form
3555 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003556 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003557 // bool operator&&(bool, bool);
3558 // bool operator||(bool, bool);
3559 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003560 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3561 /*IsAssignmentOperator=*/false,
3562 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003563 break;
3564 }
3565
3566 case OO_Subscript:
3567 // C++ [over.built]p13:
3568 //
3569 // For every cv-qualified or cv-unqualified object type T there
3570 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003571 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003572 // T* operator+(T*, ptrdiff_t); [ABOVE]
3573 // T& operator[](T*, ptrdiff_t);
3574 // T* operator-(T*, ptrdiff_t); [ABOVE]
3575 // T* operator+(ptrdiff_t, T*); [ABOVE]
3576 // T& operator[](ptrdiff_t, T*);
3577 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3578 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3579 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003580 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003581 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003582
3583 // T& operator[](T*, ptrdiff_t)
3584 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3585
3586 // T& operator[](ptrdiff_t, T*);
3587 ParamTypes[0] = ParamTypes[1];
3588 ParamTypes[1] = *Ptr;
3589 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3590 }
3591 break;
3592
3593 case OO_ArrowStar:
3594 // FIXME: No support for pointer-to-members yet.
3595 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003596
3597 case OO_Conditional:
3598 // Note that we don't consider the first argument, since it has been
3599 // contextually converted to bool long ago. The candidates below are
3600 // therefore added as binary.
3601 //
3602 // C++ [over.built]p24:
3603 // For every type T, where T is a pointer or pointer-to-member type,
3604 // there exist candidate operator functions of the form
3605 //
3606 // T operator?(bool, T, T);
3607 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00003608 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3609 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3610 QualType ParamTypes[2] = { *Ptr, *Ptr };
3611 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3612 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003613 for (BuiltinCandidateTypeSet::iterator Ptr =
3614 CandidateTypes.member_pointer_begin(),
3615 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3616 QualType ParamTypes[2] = { *Ptr, *Ptr };
3617 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3618 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003619 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00003620 }
3621}
3622
Douglas Gregore254f902009-02-04 00:32:51 +00003623/// \brief Add function candidates found via argument-dependent lookup
3624/// to the set of overloading candidates.
3625///
3626/// This routine performs argument-dependent name lookup based on the
3627/// given function name (which may also be an operator name) and adds
3628/// all of the overload candidates found by ADL to the overload
3629/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00003630void
Douglas Gregore254f902009-02-04 00:32:51 +00003631Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3632 Expr **Args, unsigned NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00003633 bool HasExplicitTemplateArgs,
3634 const TemplateArgument *ExplicitTemplateArgs,
3635 unsigned NumExplicitTemplateArgs,
3636 OverloadCandidateSet& CandidateSet,
3637 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003638 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00003639
Douglas Gregorcabea402009-09-22 15:41:20 +00003640 // FIXME: Should we be trafficking in canonical function decls throughout?
3641
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003642 // Record all of the function candidates that we've already
3643 // added to the overload set, so that we don't add those same
3644 // candidates a second time.
3645 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3646 CandEnd = CandidateSet.end();
3647 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003648 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003649 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003650 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3651 Functions.insert(FunTmpl);
3652 }
Douglas Gregore254f902009-02-04 00:32:51 +00003653
Douglas Gregorcabea402009-09-22 15:41:20 +00003654 // FIXME: Pass in the explicit template arguments?
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003655 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00003656
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003657 // Erase all of the candidates we already knew about.
3658 // FIXME: This is suboptimal. Is there a better way?
3659 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3660 CandEnd = CandidateSet.end();
3661 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003662 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003663 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003664 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3665 Functions.erase(FunTmpl);
3666 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003667
3668 // For each of the ADL candidates we found, add it to the overload
3669 // set.
3670 for (FunctionSet::iterator Func = Functions.begin(),
3671 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00003672 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003673 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
3674 if (HasExplicitTemplateArgs)
3675 continue;
3676
3677 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
3678 false, false, PartialOverloading);
3679 } else
Mike Stump11289f42009-09-09 15:08:12 +00003680 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00003681 HasExplicitTemplateArgs,
3682 ExplicitTemplateArgs,
3683 NumExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003684 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00003685 }
Douglas Gregore254f902009-02-04 00:32:51 +00003686}
3687
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003688/// isBetterOverloadCandidate - Determines whether the first overload
3689/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00003690bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003691Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00003692 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003693 // Define viable functions to be better candidates than non-viable
3694 // functions.
3695 if (!Cand2.Viable)
3696 return Cand1.Viable;
3697 else if (!Cand1.Viable)
3698 return false;
3699
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003700 // C++ [over.match.best]p1:
3701 //
3702 // -- if F is a static member function, ICS1(F) is defined such
3703 // that ICS1(F) is neither better nor worse than ICS1(G) for
3704 // any function G, and, symmetrically, ICS1(G) is neither
3705 // better nor worse than ICS1(F).
3706 unsigned StartArg = 0;
3707 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3708 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003709
Douglas Gregord3cb3562009-07-07 23:38:56 +00003710 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00003711 // A viable function F1 is defined to be a better function than another
3712 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00003713 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003714 unsigned NumArgs = Cand1.Conversions.size();
3715 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3716 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003717 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003718 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3719 Cand2.Conversions[ArgIdx])) {
3720 case ImplicitConversionSequence::Better:
3721 // Cand1 has a better conversion sequence.
3722 HasBetterConversion = true;
3723 break;
3724
3725 case ImplicitConversionSequence::Worse:
3726 // Cand1 can't be better than Cand2.
3727 return false;
3728
3729 case ImplicitConversionSequence::Indistinguishable:
3730 // Do nothing.
3731 break;
3732 }
3733 }
3734
Mike Stump11289f42009-09-09 15:08:12 +00003735 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00003736 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003737 if (HasBetterConversion)
3738 return true;
3739
Mike Stump11289f42009-09-09 15:08:12 +00003740 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00003741 // specialization, or, if not that,
3742 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3743 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3744 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003745
3746 // -- F1 and F2 are function template specializations, and the function
3747 // template for F1 is more specialized than the template for F2
3748 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00003749 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00003750 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3751 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00003752 if (FunctionTemplateDecl *BetterTemplate
3753 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3754 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00003755 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
3756 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00003757 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003758
Douglas Gregora1f013e2008-11-07 22:36:19 +00003759 // -- the context is an initialization by user-defined conversion
3760 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3761 // from the return type of F1 to the destination type (i.e.,
3762 // the type of the entity being initialized) is a better
3763 // conversion sequence than the standard conversion sequence
3764 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00003765 if (Cand1.Function && Cand2.Function &&
3766 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003767 isa<CXXConversionDecl>(Cand2.Function)) {
3768 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3769 Cand2.FinalConversion)) {
3770 case ImplicitConversionSequence::Better:
3771 // Cand1 has a better conversion sequence.
3772 return true;
3773
3774 case ImplicitConversionSequence::Worse:
3775 // Cand1 can't be better than Cand2.
3776 return false;
3777
3778 case ImplicitConversionSequence::Indistinguishable:
3779 // Do nothing
3780 break;
3781 }
3782 }
3783
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003784 return false;
3785}
3786
Mike Stump11289f42009-09-09 15:08:12 +00003787/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003788/// within an overload candidate set.
3789///
3790/// \param CandidateSet the set of candidate functions.
3791///
3792/// \param Loc the location of the function name (or operator symbol) for
3793/// which overload resolution occurs.
3794///
Mike Stump11289f42009-09-09 15:08:12 +00003795/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003796/// function, Best points to the candidate function found.
3797///
3798/// \returns The result of overload resolution.
Mike Stump11289f42009-09-09 15:08:12 +00003799Sema::OverloadingResult
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003800Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003801 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00003802 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003803 // Find the best viable function.
3804 Best = CandidateSet.end();
3805 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3806 Cand != CandidateSet.end(); ++Cand) {
3807 if (Cand->Viable) {
3808 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3809 Best = Cand;
3810 }
3811 }
3812
3813 // If we didn't find any viable functions, abort.
3814 if (Best == CandidateSet.end())
3815 return OR_No_Viable_Function;
3816
3817 // Make sure that this function is better than every other viable
3818 // function. If not, we have an ambiguity.
3819 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3820 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00003821 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003822 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00003823 !isBetterOverloadCandidate(*Best, *Cand)) {
3824 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003825 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003826 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003827 }
Mike Stump11289f42009-09-09 15:08:12 +00003828
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003829 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00003830 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00003831 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003832 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00003833 return OR_Deleted;
3834
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003835 // C++ [basic.def.odr]p2:
3836 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00003837 // when referred to from a potentially-evaluated expression. [Note: this
3838 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003839 // (clause 13), user-defined conversions (12.3.2), allocation function for
3840 // placement new (5.3.4), as well as non-default initialization (8.5).
3841 if (Best->Function)
3842 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003843 return OR_Success;
3844}
3845
3846/// PrintOverloadCandidates - When overload resolution fails, prints
3847/// diagnostic messages containing the candidates in the candidate
3848/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump11289f42009-09-09 15:08:12 +00003849void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003850Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003851 bool OnlyViable) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003852 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3853 LastCand = CandidateSet.end();
3854 for (; Cand != LastCand; ++Cand) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003855 if (Cand->Viable || !OnlyViable) {
3856 if (Cand->Function) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003857 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003858 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003859 // Deleted or "unavailable" function.
3860 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3861 << Cand->Function->isDeleted();
Douglas Gregor4fb9cde8e2009-09-15 20:11:42 +00003862 } else if (FunctionTemplateDecl *FunTmpl
3863 = Cand->Function->getPrimaryTemplate()) {
3864 // Function template specialization
3865 // FIXME: Give a better reason!
3866 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
3867 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
3868 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor171c45a2009-02-18 21:56:37 +00003869 } else {
3870 // Normal function
3871 // FIXME: Give a better reason!
3872 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3873 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00003874 } else if (Cand->IsSurrogate) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003875 // Desugar the type of the surrogate down to a function type,
3876 // retaining as many typedefs as possible while still showing
3877 // the function type (and, therefore, its parameter types).
3878 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003879 bool isLValueReference = false;
3880 bool isRValueReference = false;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003881 bool isPointer = false;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003882 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003883 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003884 FnType = FnTypeRef->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003885 isLValueReference = true;
3886 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003887 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003888 FnType = FnTypeRef->getPointeeType();
3889 isRValueReference = true;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003890 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003891 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003892 FnType = FnTypePtr->getPointeeType();
3893 isPointer = true;
3894 }
3895 // Desugar down to a function type.
John McCall9dd450b2009-09-21 23:43:11 +00003896 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003897 // Reconstruct the pointer/reference as appropriate.
3898 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003899 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3900 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003901
Douglas Gregorab7897a2008-11-19 22:57:39 +00003902 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003903 << FnType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003904 } else {
3905 // FIXME: We need to get the identifier in here
Mike Stump87c57ac2009-05-16 07:39:55 +00003906 // FIXME: Do we want the error message to point at the operator?
3907 // (built-ins won't have a location)
Mike Stump11289f42009-09-09 15:08:12 +00003908 QualType FnType
Douglas Gregora11693b2008-11-12 17:17:38 +00003909 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3910 Cand->BuiltinTypes.ParamTypes,
3911 Cand->Conversions.size(),
3912 false, 0);
3913
Chris Lattner1e5665e2008-11-24 06:25:27 +00003914 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003915 }
3916 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003917 }
3918}
3919
Douglas Gregorcd695e52008-11-10 20:40:00 +00003920/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3921/// an overloaded function (C++ [over.over]), where @p From is an
3922/// expression with overloaded function type and @p ToType is the type
3923/// we're trying to resolve to. For example:
3924///
3925/// @code
3926/// int f(double);
3927/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00003928///
Douglas Gregorcd695e52008-11-10 20:40:00 +00003929/// int (*pfd)(double) = f; // selects f(double)
3930/// @endcode
3931///
3932/// This routine returns the resulting FunctionDecl if it could be
3933/// resolved, and NULL otherwise. When @p Complain is true, this
3934/// routine will emit diagnostics if there is an error.
3935FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003936Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00003937 bool Complain) {
3938 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003939 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003940 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00003941 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003942 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00003943 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003944 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003945 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003946 FunctionType = MemTypePtr->getPointeeType();
3947 IsMember = true;
3948 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00003949
3950 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00003951 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00003952 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00003953 return 0;
3954
3955 // Find the actual overloaded function declaration.
3956 OverloadedFunctionDecl *Ovl = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003957
Douglas Gregorcd695e52008-11-10 20:40:00 +00003958 // C++ [over.over]p1:
3959 // [...] [Note: any redundant set of parentheses surrounding the
3960 // overloaded function name is ignored (5.1). ]
3961 Expr *OvlExpr = From->IgnoreParens();
3962
3963 // C++ [over.over]p1:
3964 // [...] The overloaded function name can be preceded by the &
3965 // operator.
3966 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3967 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3968 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3969 }
3970
3971 // Try to dig out the overloaded function.
Douglas Gregor9b146582009-07-08 20:55:45 +00003972 FunctionTemplateDecl *FunctionTemplate = 0;
3973 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00003974 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor9b146582009-07-08 20:55:45 +00003975 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
3976 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00003977
Mike Stump11289f42009-09-09 15:08:12 +00003978 // If there's no overloaded function declaration or function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00003979 // we're done.
3980 if (!Ovl && !FunctionTemplate)
Douglas Gregorcd695e52008-11-10 20:40:00 +00003981 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003982
Douglas Gregor9b146582009-07-08 20:55:45 +00003983 OverloadIterator Fun;
3984 if (Ovl)
3985 Fun = Ovl;
3986 else
3987 Fun = FunctionTemplate;
Mike Stump11289f42009-09-09 15:08:12 +00003988
Douglas Gregorcd695e52008-11-10 20:40:00 +00003989 // Look through all of the overloaded functions, searching for one
3990 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003991 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Mike Stump11289f42009-09-09 15:08:12 +00003992
Douglas Gregorb257e4f2009-07-08 23:33:52 +00003993 bool FoundNonTemplateFunction = false;
Douglas Gregor9b146582009-07-08 20:55:45 +00003994 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00003995 // C++ [over.over]p3:
3996 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00003997 // targets of type "pointer-to-function" or "reference-to-function."
3998 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003999 // type "pointer-to-member-function."
4000 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004001
Mike Stump11289f42009-09-09 15:08:12 +00004002 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregor9b146582009-07-08 20:55:45 +00004003 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Mike Stump11289f42009-09-09 15:08:12 +00004004 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004005 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004006 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004007 // static when converting to member pointer.
4008 if (Method->isStatic() == IsMember)
4009 continue;
4010 } else if (IsMember)
4011 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004012
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004013 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004014 // If the name is a function template, template argument deduction is
4015 // done (14.8.2.2), and if the argument deduction succeeds, the
4016 // resulting template argument list is used to generate a single
4017 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004018 // overloaded functions considered.
Douglas Gregor9b146582009-07-08 20:55:45 +00004019 FunctionDecl *Specialization = 0;
4020 TemplateDeductionInfo Info(Context);
4021 if (TemplateDeductionResult Result
4022 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
4023 /*FIXME:*/0, /*FIXME:*/0,
4024 FunctionType, Specialization, Info)) {
4025 // FIXME: make a note of the failed deduction for diagnostics.
4026 (void)Result;
4027 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004028 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004029 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004030 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004031 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004032 }
4033 }
Mike Stump11289f42009-09-09 15:08:12 +00004034
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004035 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
4036 // Skip non-static functions when converting to pointer, and static
4037 // when converting to member pointer.
4038 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004039 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004040 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004041 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004042
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004043 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004044 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004045 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004046 FoundNonTemplateFunction = true;
4047 }
Mike Stump11289f42009-09-09 15:08:12 +00004048 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004049 }
4050
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004051 // If there were 0 or 1 matches, we're done.
4052 if (Matches.empty())
4053 return 0;
4054 else if (Matches.size() == 1)
4055 return *Matches.begin();
4056
4057 // C++ [over.over]p4:
4058 // If more than one function is selected, [...]
4059 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
Douglas Gregor05155d82009-08-21 23:19:43 +00004060 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004061 if (FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004062 // [...] any function template specializations in the set are
4063 // eliminated if the set also contains a non-template function, [...]
4064 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004065 if ((*M)->getPrimaryTemplate() == 0)
4066 RemainingMatches.push_back(*M);
4067 } else {
Douglas Gregor05155d82009-08-21 23:19:43 +00004068 // [...] and any given function template specialization F1 is
4069 // eliminated if the set contains a second function template
4070 // specialization whose function template is more specialized
4071 // than the function template of F1 according to the partial
4072 // ordering rules of 14.5.5.2.
4073
4074 // The algorithm specified above is quadratic. We instead use a
4075 // two-pass algorithm (similar to the one used to identify the
4076 // best viable function in an overload set) that identifies the
4077 // best function template (if it exists).
4078 MatchIter Best = Matches.begin();
4079 MatchIter M = Best, MEnd = Matches.end();
4080 // Find the most specialized function.
4081 for (++M; M != MEnd; ++M)
4082 if (getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4083 (*Best)->getPrimaryTemplate(),
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004084 TPOC_Other)
Douglas Gregor05155d82009-08-21 23:19:43 +00004085 == (*M)->getPrimaryTemplate())
4086 Best = M;
4087
4088 // Determine whether this function template is more specialized
4089 // that all of the others.
4090 bool Ambiguous = false;
4091 for (M = Matches.begin(); M != MEnd; ++M) {
4092 if (M != Best &&
4093 getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4094 (*Best)->getPrimaryTemplate(),
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004095 TPOC_Other)
Douglas Gregor05155d82009-08-21 23:19:43 +00004096 != (*Best)->getPrimaryTemplate()) {
4097 Ambiguous = true;
4098 break;
4099 }
4100 }
4101
4102 // If one function template was more specialized than all of the
4103 // others, return it.
4104 if (!Ambiguous)
4105 return *Best;
4106
4107 // We could not find a most-specialized function template, which
4108 // is equivalent to having a set of function templates with more
4109 // than one such template. So, we place all of the function
4110 // templates into the set of remaining matches and produce a
4111 // diagnostic below. FIXME: we could perform the quadratic
4112 // algorithm here, pruning the result set to limit the number of
4113 // candidates output later.
Douglas Gregor48bc3742009-09-14 22:02:01 +00004114 RemainingMatches.append(Matches.begin(), Matches.end());
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004115 }
Mike Stump11289f42009-09-09 15:08:12 +00004116
4117 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004118 // selected function.
4119 if (RemainingMatches.size() == 1)
4120 return RemainingMatches.front();
Mike Stump11289f42009-09-09 15:08:12 +00004121
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004122 // FIXME: We should probably return the same thing that BestViableFunction
4123 // returns (even if we issue the diagnostics here).
4124 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4125 << RemainingMatches[0]->getDeclName();
4126 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4127 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004128 return 0;
4129}
4130
Douglas Gregorcabea402009-09-22 15:41:20 +00004131/// \brief Add a single candidate to the overload set.
4132static void AddOverloadedCallCandidate(Sema &S,
4133 AnyFunctionDecl Callee,
4134 bool &ArgumentDependentLookup,
4135 bool HasExplicitTemplateArgs,
4136 const TemplateArgument *ExplicitTemplateArgs,
4137 unsigned NumExplicitTemplateArgs,
4138 Expr **Args, unsigned NumArgs,
4139 OverloadCandidateSet &CandidateSet,
4140 bool PartialOverloading) {
4141 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
4142 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
4143 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4144 PartialOverloading);
4145
4146 if (Func->getDeclContext()->isRecord() ||
4147 Func->getDeclContext()->isFunctionOrMethod())
4148 ArgumentDependentLookup = false;
4149 return;
4150 }
4151
4152 FunctionTemplateDecl *FuncTemplate = cast<FunctionTemplateDecl>(Callee);
4153 S.AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4154 ExplicitTemplateArgs,
4155 NumExplicitTemplateArgs,
4156 Args, NumArgs, CandidateSet);
4157
4158 if (FuncTemplate->getDeclContext()->isRecord())
4159 ArgumentDependentLookup = false;
4160}
4161
4162/// \brief Add the overload candidates named by callee and/or found by argument
4163/// dependent lookup to the given overload set.
4164void Sema::AddOverloadedCallCandidates(NamedDecl *Callee,
4165 DeclarationName &UnqualifiedName,
4166 bool &ArgumentDependentLookup,
4167 bool HasExplicitTemplateArgs,
4168 const TemplateArgument *ExplicitTemplateArgs,
4169 unsigned NumExplicitTemplateArgs,
4170 Expr **Args, unsigned NumArgs,
4171 OverloadCandidateSet &CandidateSet,
4172 bool PartialOverloading) {
4173 // Add the functions denoted by Callee to the set of candidate
4174 // functions. While we're doing so, track whether argument-dependent
4175 // lookup still applies, per:
4176 //
4177 // C++0x [basic.lookup.argdep]p3:
4178 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4179 // and let Y be the lookup set produced by argument dependent
4180 // lookup (defined as follows). If X contains
4181 //
4182 // -- a declaration of a class member, or
4183 //
4184 // -- a block-scope function declaration that is not a
4185 // using-declaration (FIXME: check for using declaration), or
4186 //
4187 // -- a declaration that is neither a function or a function
4188 // template
4189 //
4190 // then Y is empty.
4191 if (!Callee) {
4192 // Nothing to do.
4193 } else if (OverloadedFunctionDecl *Ovl
4194 = dyn_cast<OverloadedFunctionDecl>(Callee)) {
4195 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4196 FuncEnd = Ovl->function_end();
4197 Func != FuncEnd; ++Func)
4198 AddOverloadedCallCandidate(*this, *Func, ArgumentDependentLookup,
4199 HasExplicitTemplateArgs,
4200 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4201 Args, NumArgs, CandidateSet,
4202 PartialOverloading);
4203 } else if (isa<FunctionDecl>(Callee) || isa<FunctionTemplateDecl>(Callee))
4204 AddOverloadedCallCandidate(*this,
4205 AnyFunctionDecl::getFromNamedDecl(Callee),
4206 ArgumentDependentLookup,
4207 HasExplicitTemplateArgs,
4208 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4209 Args, NumArgs, CandidateSet,
4210 PartialOverloading);
4211 // FIXME: assert isa<FunctionDecl> || isa<FunctionTemplateDecl> rather than
4212 // checking dynamically.
4213
4214 if (Callee)
4215 UnqualifiedName = Callee->getDeclName();
4216
4217 if (ArgumentDependentLookup)
4218 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
4219 HasExplicitTemplateArgs,
4220 ExplicitTemplateArgs,
4221 NumExplicitTemplateArgs,
4222 CandidateSet,
4223 PartialOverloading);
4224}
4225
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004226/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00004227/// (which eventually refers to the declaration Func) and the call
4228/// arguments Args/NumArgs, attempt to resolve the function call down
4229/// to a specific function. If overload resolution succeeds, returns
4230/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00004231/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004232/// arguments and Fn, and returns NULL.
Douglas Gregore254f902009-02-04 00:32:51 +00004233FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004234 DeclarationName UnqualifiedName,
Douglas Gregor89026b52009-06-30 23:57:56 +00004235 bool HasExplicitTemplateArgs,
4236 const TemplateArgument *ExplicitTemplateArgs,
4237 unsigned NumExplicitTemplateArgs,
Douglas Gregora60a6912008-11-26 06:01:48 +00004238 SourceLocation LParenLoc,
4239 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004240 SourceLocation *CommaLocs,
Douglas Gregore254f902009-02-04 00:32:51 +00004241 SourceLocation RParenLoc,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004242 bool &ArgumentDependentLookup) {
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004243 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004244
4245 // Add the functions denoted by Callee to the set of candidate
Douglas Gregorcabea402009-09-22 15:41:20 +00004246 // functions.
4247 AddOverloadedCallCandidates(Callee, UnqualifiedName, ArgumentDependentLookup,
4248 HasExplicitTemplateArgs, ExplicitTemplateArgs,
4249 NumExplicitTemplateArgs, Args, NumArgs,
4250 CandidateSet);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004251 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004252 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregora60a6912008-11-26 06:01:48 +00004253 case OR_Success:
4254 return Best->Function;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004255
4256 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00004257 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004258 diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004259 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004260 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4261 break;
4262
4263 case OR_Ambiguous:
4264 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004265 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004266 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4267 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004268
4269 case OR_Deleted:
4270 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4271 << Best->Function->isDeleted()
4272 << UnqualifiedName
4273 << Fn->getSourceRange();
4274 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4275 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004276 }
4277
4278 // Overload resolution failed. Destroy all of the subexpressions and
4279 // return NULL.
4280 Fn->Destroy(Context);
4281 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4282 Args[Arg]->Destroy(Context);
4283 return 0;
4284}
4285
Douglas Gregor084d8552009-03-13 23:49:33 +00004286/// \brief Create a unary operation that may resolve to an overloaded
4287/// operator.
4288///
4289/// \param OpLoc The location of the operator itself (e.g., '*').
4290///
4291/// \param OpcIn The UnaryOperator::Opcode that describes this
4292/// operator.
4293///
4294/// \param Functions The set of non-member functions that will be
4295/// considered by overload resolution. The caller needs to build this
4296/// set based on the context using, e.g.,
4297/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4298/// set should not contain any member functions; those will be added
4299/// by CreateOverloadedUnaryOp().
4300///
4301/// \param input The input argument.
4302Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4303 unsigned OpcIn,
4304 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00004305 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004306 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4307 Expr *Input = (Expr *)input.get();
4308
4309 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4310 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4311 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4312
4313 Expr *Args[2] = { Input, 0 };
4314 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004315
Douglas Gregor084d8552009-03-13 23:49:33 +00004316 // For post-increment and post-decrement, add the implicit '0' as
4317 // the second argument, so that we know this is a post-increment or
4318 // post-decrement.
4319 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4320 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00004321 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00004322 SourceLocation());
4323 NumArgs = 2;
4324 }
4325
4326 if (Input->isTypeDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00004327 OverloadedFunctionDecl *Overloads
Douglas Gregor084d8552009-03-13 23:49:33 +00004328 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004329 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00004330 FuncEnd = Functions.end();
4331 Func != FuncEnd; ++Func)
4332 Overloads->addOverload(*Func);
4333
4334 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4335 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004336
Douglas Gregor084d8552009-03-13 23:49:33 +00004337 input.release();
4338 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4339 &Args[0], NumArgs,
4340 Context.DependentTy,
4341 OpLoc));
4342 }
4343
4344 // Build an empty overload set.
4345 OverloadCandidateSet CandidateSet;
4346
4347 // Add the candidates from the given function set.
4348 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4349
4350 // Add operator candidates that are member functions.
4351 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4352
4353 // Add builtin operator candidates.
4354 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4355
4356 // Perform overload resolution.
4357 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004358 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004359 case OR_Success: {
4360 // We found a built-in operator or an overloaded operator.
4361 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00004362
Douglas Gregor084d8552009-03-13 23:49:33 +00004363 if (FnDecl) {
4364 // We matched an overloaded operator. Build a call to that
4365 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00004366
Douglas Gregor084d8552009-03-13 23:49:33 +00004367 // Convert the arguments.
4368 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4369 if (PerformObjectArgumentInitialization(Input, Method))
4370 return ExprError();
4371 } else {
4372 // Convert the arguments.
4373 if (PerformCopyInitialization(Input,
4374 FnDecl->getParamDecl(0)->getType(),
4375 "passing"))
4376 return ExprError();
4377 }
4378
4379 // Determine the result type
4380 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00004381 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor084d8552009-03-13 23:49:33 +00004382 ResultTy = ResultTy.getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004383
Douglas Gregor084d8552009-03-13 23:49:33 +00004384 // Build the actual expression node.
4385 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4386 SourceLocation());
4387 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004388
Douglas Gregor084d8552009-03-13 23:49:33 +00004389 input.release();
Mike Stump11289f42009-09-09 15:08:12 +00004390
4391 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlssone80ccac2009-08-16 04:11:06 +00004392 &Input, 1, ResultTy, OpLoc);
4393 return MaybeBindToTemporary(CE);
Douglas Gregor084d8552009-03-13 23:49:33 +00004394 } else {
4395 // We matched a built-in operator. Convert the arguments, then
4396 // break out so that we will build the appropriate built-in
4397 // operator node.
4398 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4399 Best->Conversions[0], "passing"))
4400 return ExprError();
4401
4402 break;
4403 }
4404 }
4405
4406 case OR_No_Viable_Function:
4407 // No viable function; fall through to handling this as a
4408 // built-in operator, which will produce an error message for us.
4409 break;
4410
4411 case OR_Ambiguous:
4412 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4413 << UnaryOperator::getOpcodeStr(Opc)
4414 << Input->getSourceRange();
4415 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4416 return ExprError();
4417
4418 case OR_Deleted:
4419 Diag(OpLoc, diag::err_ovl_deleted_oper)
4420 << Best->Function->isDeleted()
4421 << UnaryOperator::getOpcodeStr(Opc)
4422 << Input->getSourceRange();
4423 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4424 return ExprError();
4425 }
4426
4427 // Either we found no viable overloaded operator or we matched a
4428 // built-in operator. In either case, fall through to trying to
4429 // build a built-in operation.
4430 input.release();
4431 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4432}
4433
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004434/// \brief Create a binary operation that may resolve to an overloaded
4435/// operator.
4436///
4437/// \param OpLoc The location of the operator itself (e.g., '+').
4438///
4439/// \param OpcIn The BinaryOperator::Opcode that describes this
4440/// operator.
4441///
4442/// \param Functions The set of non-member functions that will be
4443/// considered by overload resolution. The caller needs to build this
4444/// set based on the context using, e.g.,
4445/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4446/// set should not contain any member functions; those will be added
4447/// by CreateOverloadedBinOp().
4448///
4449/// \param LHS Left-hand argument.
4450/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00004451Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004452Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004453 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004454 FunctionSet &Functions,
4455 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004456 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00004457 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004458
4459 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4460 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4461 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4462
4463 // If either side is type-dependent, create an appropriate dependent
4464 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00004465 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004466 // .* cannot be overloaded.
4467 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004468 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004469 Context.DependentTy, OpLoc));
4470
Mike Stump11289f42009-09-09 15:08:12 +00004471 OverloadedFunctionDecl *Overloads
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004472 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004473 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004474 FuncEnd = Functions.end();
4475 Func != FuncEnd; ++Func)
4476 Overloads->addOverload(*Func);
4477
4478 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4479 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004480
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004481 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00004482 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004483 Context.DependentTy,
4484 OpLoc));
4485 }
4486
4487 // If this is the .* operator, which is not overloadable, just
4488 // create a built-in binary operator.
4489 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004490 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004491
4492 // If this is one of the assignment operators, we only perform
4493 // overload resolution if the left-hand side is a class or
4494 // enumeration type (C++ [expr.ass]p3).
4495 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregore9899d92009-08-26 17:08:25 +00004496 !Args[0]->getType()->isOverloadableType())
4497 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004498
Douglas Gregor084d8552009-03-13 23:49:33 +00004499 // Build an empty overload set.
4500 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004501
4502 // Add the candidates from the given function set.
4503 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4504
4505 // Add operator candidates that are member functions.
4506 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4507
4508 // Add builtin operator candidates.
4509 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4510
4511 // Perform overload resolution.
4512 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004513 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004514 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004515 // We found a built-in operator or an overloaded operator.
4516 FunctionDecl *FnDecl = Best->Function;
4517
4518 if (FnDecl) {
4519 // We matched an overloaded operator. Build a call to that
4520 // operator.
4521
4522 // Convert the arguments.
4523 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregore9899d92009-08-26 17:08:25 +00004524 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4525 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004526 "passing"))
4527 return ExprError();
4528 } else {
4529 // Convert the arguments.
Douglas Gregore9899d92009-08-26 17:08:25 +00004530 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004531 "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004532 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004533 "passing"))
4534 return ExprError();
4535 }
4536
4537 // Determine the result type
4538 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00004539 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004540 ResultTy = ResultTy.getNonReferenceType();
4541
4542 // Build the actual expression node.
4543 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00004544 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004545 UsualUnaryConversions(FnExpr);
4546
Mike Stump11289f42009-09-09 15:08:12 +00004547 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlssone80ccac2009-08-16 04:11:06 +00004548 Args, 2, ResultTy, OpLoc);
4549 return MaybeBindToTemporary(CE);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004550 } else {
4551 // We matched a built-in operator. Convert the arguments, then
4552 // break out so that we will build the appropriate built-in
4553 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00004554 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004555 Best->Conversions[0], "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004556 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004557 Best->Conversions[1], "passing"))
4558 return ExprError();
4559
4560 break;
4561 }
4562 }
4563
4564 case OR_No_Viable_Function:
Sebastian Redl027de2a2009-05-21 11:50:50 +00004565 // For class as left operand for assignment or compound assigment operator
4566 // do not fall through to handling in built-in, but report that no overloaded
4567 // assignment operator found
Douglas Gregore9899d92009-08-26 17:08:25 +00004568 if (Args[0]->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00004569 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4570 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004571 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Sebastian Redl027de2a2009-05-21 11:50:50 +00004572 return ExprError();
4573 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004574 // No viable function; fall through to handling this as a
4575 // built-in operator, which will produce an error message for us.
4576 break;
4577
4578 case OR_Ambiguous:
4579 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4580 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004581 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004582 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4583 return ExprError();
4584
4585 case OR_Deleted:
4586 Diag(OpLoc, diag::err_ovl_deleted_oper)
4587 << Best->Function->isDeleted()
4588 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004589 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004590 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4591 return ExprError();
4592 }
4593
4594 // Either we found no viable overloaded operator or we matched a
4595 // built-in operator. In either case, try to build a built-in
4596 // operation.
Douglas Gregore9899d92009-08-26 17:08:25 +00004597 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004598}
4599
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004600/// BuildCallToMemberFunction - Build a call to a member
4601/// function. MemExpr is the expression that refers to the member
4602/// function (and includes the object parameter), Args/NumArgs are the
4603/// arguments to the function call (not including the object
4604/// parameter). The caller needs to validate that the member
4605/// expression refers to a member function or an overloaded member
4606/// function.
4607Sema::ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00004608Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4609 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004610 unsigned NumArgs, SourceLocation *CommaLocs,
4611 SourceLocation RParenLoc) {
4612 // Dig out the member expression. This holds both the object
4613 // argument and the member function we're referring to.
4614 MemberExpr *MemExpr = 0;
4615 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4616 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4617 else
4618 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4619 assert(MemExpr && "Building member call without member expression");
4620
4621 // Extract the object argument.
4622 Expr *ObjectArg = MemExpr->getBase();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004623
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004624 CXXMethodDecl *Method = 0;
Douglas Gregor97628d62009-08-21 00:16:32 +00004625 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4626 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004627 // Add overload candidates
4628 OverloadCandidateSet CandidateSet;
Douglas Gregor97628d62009-08-21 00:16:32 +00004629 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004630
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004631 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4632 Func != FuncEnd; ++Func) {
4633 if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
Mike Stump11289f42009-09-09 15:08:12 +00004634 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004635 /*SuppressUserConversions=*/false);
4636 else
Douglas Gregor84f14dd2009-09-01 00:37:14 +00004637 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4638 MemExpr->hasExplicitTemplateArgumentList(),
4639 MemExpr->getTemplateArgs(),
4640 MemExpr->getNumTemplateArgs(),
4641 ObjectArg, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004642 CandidateSet,
4643 /*SuppressUsedConversions=*/false);
4644 }
Mike Stump11289f42009-09-09 15:08:12 +00004645
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004646 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004647 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004648 case OR_Success:
4649 Method = cast<CXXMethodDecl>(Best->Function);
4650 break;
4651
4652 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00004653 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004654 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00004655 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004656 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4657 // FIXME: Leaking incoming expressions!
4658 return true;
4659
4660 case OR_Ambiguous:
Mike Stump11289f42009-09-09 15:08:12 +00004661 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004662 diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00004663 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004664 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4665 // FIXME: Leaking incoming expressions!
4666 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004667
4668 case OR_Deleted:
Mike Stump11289f42009-09-09 15:08:12 +00004669 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00004670 diag::err_ovl_deleted_member_call)
4671 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00004672 << DeclName << MemExprE->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00004673 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4674 // FIXME: Leaking incoming expressions!
4675 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004676 }
4677
4678 FixOverloadedFunctionReference(MemExpr, Method);
4679 } else {
4680 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4681 }
4682
4683 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00004684 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004685 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
Mike Stump11289f42009-09-09 15:08:12 +00004686 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004687 Method->getResultType().getNonReferenceType(),
4688 RParenLoc));
4689
4690 // Convert the object argument (for a non-static member function call).
Mike Stump11289f42009-09-09 15:08:12 +00004691 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004692 PerformObjectArgumentInitialization(ObjectArg, Method))
4693 return true;
4694 MemExpr->setBase(ObjectArg);
4695
4696 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004697 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004698 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004699 RParenLoc))
4700 return true;
4701
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004702 if (CheckFunctionCall(Method, TheCall.get()))
4703 return true;
Anders Carlsson8c84c202009-08-16 03:42:12 +00004704
4705 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004706}
4707
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004708/// BuildCallToObjectOfClassType - Build a call to an object of class
4709/// type (C++ [over.call.object]), which can end up invoking an
4710/// overloaded function call operator (@c operator()) or performing a
4711/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00004712Sema::ExprResult
4713Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00004714 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004715 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004716 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004717 SourceLocation RParenLoc) {
4718 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004719 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00004720
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004721 // C++ [over.call.object]p1:
4722 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00004723 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004724 // candidate functions includes at least the function call
4725 // operators of T. The function call operators of T are obtained by
4726 // ordinary lookup of the name operator() in the context of
4727 // (E).operator().
4728 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00004729 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor55297ac2008-12-23 00:26:44 +00004730 DeclContext::lookup_const_iterator Oper, OperEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004731 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor55297ac2008-12-23 00:26:44 +00004732 Oper != OperEnd; ++Oper)
Mike Stump11289f42009-09-09 15:08:12 +00004733 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
Douglas Gregor55297ac2008-12-23 00:26:44 +00004734 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004735
Douglas Gregorab7897a2008-11-19 22:57:39 +00004736 // C++ [over.call.object]p2:
4737 // In addition, for each conversion function declared in T of the
4738 // form
4739 //
4740 // operator conversion-type-id () cv-qualifier;
4741 //
4742 // where cv-qualifier is the same cv-qualification as, or a
4743 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00004744 // denotes the type "pointer to function of (P1,...,Pn) returning
4745 // R", or the type "reference to pointer to function of
4746 // (P1,...,Pn) returning R", or the type "reference to function
4747 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00004748 // is also considered as a candidate function. Similarly,
4749 // surrogate call functions are added to the set of candidate
4750 // functions for each conversion function declared in an
4751 // accessible base class provided the function is not hidden
4752 // within T by another intervening declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004753
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004754 if (!RequireCompleteType(SourceLocation(), Object->getType(), 0)) {
4755 // FIXME: Look in base classes for more conversion operators!
Mike Stump11289f42009-09-09 15:08:12 +00004756 OverloadedFunctionDecl *Conversions
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004757 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00004758 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004759 Func = Conversions->function_begin(),
4760 FuncEnd = Conversions->function_end();
4761 Func != FuncEnd; ++Func) {
4762 CXXConversionDecl *Conv;
4763 FunctionTemplateDecl *ConvTemplate;
4764 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Douglas Gregor05155d82009-08-21 23:19:43 +00004765
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004766 // Skip over templated conversion functions; they aren't
4767 // surrogates.
4768 if (ConvTemplate)
4769 continue;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004770
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004771 // Strip the reference type (if any) and then the pointer type (if
4772 // any) to get down to what might be a function type.
4773 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4774 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4775 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004776
John McCall9dd450b2009-09-21 23:43:11 +00004777 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004778 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4779 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00004780 }
Mike Stump11289f42009-09-09 15:08:12 +00004781
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004782 // Perform overload resolution.
4783 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004784 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004785 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00004786 // Overload resolution succeeded; we'll build the appropriate call
4787 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004788 break;
4789
4790 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00004791 Diag(Object->getSourceRange().getBegin(),
Sebastian Redl15b02d22008-11-22 13:44:36 +00004792 diag::err_ovl_no_viable_object_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004793 << Object->getType() << Object->getSourceRange();
Sebastian Redl15b02d22008-11-22 13:44:36 +00004794 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004795 break;
4796
4797 case OR_Ambiguous:
4798 Diag(Object->getSourceRange().getBegin(),
4799 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004800 << Object->getType() << Object->getSourceRange();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004801 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4802 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004803
4804 case OR_Deleted:
4805 Diag(Object->getSourceRange().getBegin(),
4806 diag::err_ovl_deleted_object_call)
4807 << Best->Function->isDeleted()
4808 << Object->getType() << Object->getSourceRange();
4809 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4810 break;
Mike Stump11289f42009-09-09 15:08:12 +00004811 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004812
Douglas Gregorab7897a2008-11-19 22:57:39 +00004813 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004814 // We had an error; delete all of the subexpressions and return
4815 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00004816 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004817 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00004818 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004819 return true;
4820 }
4821
Douglas Gregorab7897a2008-11-19 22:57:39 +00004822 if (Best->Function == 0) {
4823 // Since there is no function declaration, this is one of the
4824 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00004825 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00004826 = cast<CXXConversionDecl>(
4827 Best->Conversions[0].UserDefined.ConversionFunction);
4828
4829 // We selected one of the surrogate functions that converts the
4830 // object parameter to a function pointer. Perform the conversion
4831 // on the object argument, then let ActOnCallExpr finish the job.
4832 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004833 ImpCastExprToType(Object,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004834 Conv->getConversionType().getNonReferenceType(),
Anders Carlssona076d142009-07-31 01:23:52 +00004835 CastExpr::CK_Unknown,
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004836 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004837 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4838 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4839 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004840 }
4841
4842 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4843 // that calls this method, using Object for the implicit object
4844 // parameter and passing along the remaining arguments.
4845 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00004846 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004847
4848 unsigned NumArgsInProto = Proto->getNumArgs();
4849 unsigned NumArgsToCheck = NumArgs;
4850
4851 // Build the full argument list for the method call (the
4852 // implicit object parameter is placed at the beginning of the
4853 // list).
4854 Expr **MethodArgs;
4855 if (NumArgs < NumArgsInProto) {
4856 NumArgsToCheck = NumArgsInProto;
4857 MethodArgs = new Expr*[NumArgsInProto + 1];
4858 } else {
4859 MethodArgs = new Expr*[NumArgs + 1];
4860 }
4861 MethodArgs[0] = Object;
4862 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4863 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00004864
4865 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004866 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004867 UsualUnaryConversions(NewFn);
4868
4869 // Once we've built TheCall, all of the expressions are properly
4870 // owned.
4871 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004872 ExprOwningPtr<CXXOperatorCallExpr>
4873 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004874 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00004875 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004876 delete [] MethodArgs;
4877
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004878 // We may have default arguments. If so, we need to allocate more
4879 // slots in the call for them.
4880 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00004881 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004882 else if (NumArgs > NumArgsInProto)
4883 NumArgsToCheck = NumArgsInProto;
4884
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004885 bool IsError = false;
4886
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004887 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004888 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004889 TheCall->setArg(0, Object);
4890
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004891
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004892 // Check the argument types.
4893 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004894 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004895 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004896 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00004897
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004898 // Pass the argument.
4899 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004900 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004901 } else {
Anders Carlssone8271232009-08-14 18:30:22 +00004902 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004903 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004904
4905 TheCall->setArg(i + 1, Arg);
4906 }
4907
4908 // If this is a variadic call, handle args passed through "...".
4909 if (Proto->isVariadic()) {
4910 // Promote the arguments (C99 6.5.2.2p7).
4911 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4912 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004913 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004914 TheCall->setArg(i + 1, Arg);
4915 }
4916 }
4917
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004918 if (IsError) return true;
4919
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004920 if (CheckFunctionCall(Method, TheCall.get()))
4921 return true;
4922
Anders Carlsson1c83deb2009-08-16 03:53:54 +00004923 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004924}
4925
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004926/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00004927/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004928/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00004929Sema::OwningExprResult
4930Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
4931 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004932 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00004933
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004934 // C++ [over.ref]p1:
4935 //
4936 // [...] An expression x->m is interpreted as (x.operator->())->m
4937 // for a class object x of type T if T::operator->() exists and if
4938 // the operator is selected as the best match function by the
4939 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004940 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4941 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004942 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00004943
Anders Carlsson78b54932009-09-10 23:18:36 +00004944 LookupResult R = LookupQualifiedName(BaseRecord->getDecl(), OpName,
4945 LookupOrdinaryName);
4946
4947 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
4948 Oper != OperEnd; ++Oper)
Douglas Gregor55297ac2008-12-23 00:26:44 +00004949 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004950 /*SuppressUserConversions=*/false);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004951
4952 // Perform overload resolution.
4953 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004954 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004955 case OR_Success:
4956 // Overload resolution succeeded; we'll build the call below.
4957 break;
4958
4959 case OR_No_Viable_Function:
4960 if (CandidateSet.empty())
4961 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00004962 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004963 else
4964 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00004965 << "operator->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004966 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregord8061562009-08-06 03:17:00 +00004967 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004968
4969 case OR_Ambiguous:
4970 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00004971 << "->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004972 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00004973 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00004974
4975 case OR_Deleted:
4976 Diag(OpLoc, diag::err_ovl_deleted_oper)
4977 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00004978 << "->" << Base->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00004979 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00004980 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004981 }
4982
4983 // Convert the object parameter.
4984 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00004985 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00004986 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00004987
4988 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00004989 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004990
4991 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00004992 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4993 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004994 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004995 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004996 Method->getResultType().getNonReferenceType(),
4997 OpLoc);
Douglas Gregord8061562009-08-06 03:17:00 +00004998 return Owned(Base);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004999}
5000
Douglas Gregorcd695e52008-11-10 20:40:00 +00005001/// FixOverloadedFunctionReference - E is an expression that refers to
5002/// a C++ overloaded function (possibly with some parentheses and
5003/// perhaps a '&' around it). We have resolved the overloaded function
5004/// to the function declaration Fn, so patch up the expression E to
5005/// refer (possibly indirectly) to Fn.
5006void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
5007 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5008 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5009 E->setType(PE->getSubExpr()->getType());
5010 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00005011 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00005012 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005013 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5014 if (Method->isStatic()) {
5015 // Do nothing: static member functions aren't any different
5016 // from non-member functions.
Mike Stump11289f42009-09-09 15:08:12 +00005017 } else if (QualifiedDeclRefExpr *DRE
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005018 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
5019 // We have taken the address of a pointer to member
5020 // function. Perform the computation here so that we get the
5021 // appropriate pointer to member type.
5022 DRE->setDecl(Fn);
5023 DRE->setType(Fn->getType());
5024 QualType ClassType
5025 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
Mike Stump11289f42009-09-09 15:08:12 +00005026 E->setType(Context.getMemberPointerType(Fn->getType(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005027 ClassType.getTypePtr()));
5028 return;
5029 }
5030 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005031 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005032 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregorcd695e52008-11-10 20:40:00 +00005033 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor9b146582009-07-08 20:55:45 +00005034 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
Mike Stump11289f42009-09-09 15:08:12 +00005035 isa<FunctionTemplateDecl>(DR->getDecl())) &&
Douglas Gregor9b146582009-07-08 20:55:45 +00005036 "Expected overloaded function or function template");
Douglas Gregorcd695e52008-11-10 20:40:00 +00005037 DR->setDecl(Fn);
5038 E->setType(Fn->getType());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005039 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
5040 MemExpr->setMemberDecl(Fn);
5041 E->setType(Fn->getType());
Douglas Gregorcd695e52008-11-10 20:40:00 +00005042 } else {
5043 assert(false && "Invalid reference to overloaded function");
5044 }
5045}
5046
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005047} // end namespace clang