blob: 4232d54f4b64e13bd324659c660dc047c29d3176 [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;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000414 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson228eea32009-08-28 15:33:32 +0000415 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000416 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000417 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000418 (UserDefResult = IsUserDefinedConversion(From, ToType,
419 ICS.UserDefined,
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000420 Conversions,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000421 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000422 ForceRValue)) == OR_Success) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000423 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor05379422008-11-03 17:51:48 +0000424 // C++ [over.ics.user]p4:
425 // A conversion of an expression of class type to the same class
426 // type is given Exact Match rank, and a conversion of an
427 // expression of class type to a base class of that type is
428 // given Conversion rank, in spite of the fact that a copy
429 // constructor (i.e., a user-defined conversion function) is
430 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000431 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000432 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000433 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000434 = Context.getCanonicalType(From->getType().getUnqualifiedType());
435 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
436 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000437 // Turn this into a "standard" conversion sequence, so that it
438 // gets ranked with standard conversion sequences.
Douglas Gregor05379422008-11-03 17:51:48 +0000439 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
440 ICS.Standard.setAsIdentityConversion();
441 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
442 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000443 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000444 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000445 ICS.Standard.Second = ICK_Derived_To_Base;
446 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000447 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000448
449 // C++ [over.best.ics]p4:
450 // However, when considering the argument of a user-defined
451 // conversion function that is a candidate by 13.3.1.3 when
452 // invoked for the copying of the temporary in the second step
453 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
454 // 13.3.1.6 in all cases, only standard conversion sequences and
455 // ellipsis conversion sequences are allowed.
456 if (SuppressUserConversions &&
457 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
458 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000459 } else {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000460 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000461 if (UserDefResult == OR_Ambiguous) {
462 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
463 Cand != Conversions.end(); ++Cand)
464 ICS.ConversionFunctionSet.push_back(Cand->Function);
465 }
466 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000467
468 return ICS;
469}
470
471/// IsStandardConversion - Determines whether there is a standard
472/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
473/// expression From to the type ToType. Standard conversion sequences
474/// only consider non-class types; for conversions that involve class
475/// types, use TryImplicitConversion. If a conversion exists, SCS will
476/// contain the standard conversion sequence required to perform this
477/// conversion and this routine will return true. Otherwise, this
478/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000479bool
480Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000481 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000482 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000483 QualType FromType = From->getType();
484
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000485 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000486 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000487 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000488 SCS.IncompatibleObjC = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000489 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000490 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000492 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000493 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000494 if (FromType->isRecordType() || ToType->isRecordType()) {
495 if (getLangOptions().CPlusPlus)
496 return false;
497
Mike Stump11289f42009-09-09 15:08:12 +0000498 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000499 }
500
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000501 // The first conversion can be an lvalue-to-rvalue conversion,
502 // array-to-pointer conversion, or function-to-pointer conversion
503 // (C++ 4p1).
504
Mike Stump11289f42009-09-09 15:08:12 +0000505 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000506 // An lvalue (3.10) of a non-function, non-array type T can be
507 // converted to an rvalue.
508 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000509 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000510 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000511 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000512 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000513
514 // If T is a non-class type, the type of the rvalue is the
515 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000516 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
517 // just strip the qualifiers because they don't matter.
518
519 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000520 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000521 } else if (FromType->isArrayType()) {
522 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000523 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000524
525 // An lvalue or rvalue of type "array of N T" or "array of unknown
526 // bound of T" can be converted to an rvalue of type "pointer to
527 // T" (C++ 4.2p1).
528 FromType = Context.getArrayDecayedType(FromType);
529
530 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
531 // This conversion is deprecated. (C++ D.4).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000532 SCS.Deprecated = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000533
534 // For the purpose of ranking in overload resolution
535 // (13.3.3.1.1), this conversion is considered an
536 // array-to-pointer conversion followed by a qualification
537 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000538 SCS.Second = ICK_Identity;
539 SCS.Third = ICK_Qualification;
540 SCS.ToTypePtr = ToType.getAsOpaquePtr();
541 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000542 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000543 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
544 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000545 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000546
547 // An lvalue of function type T can be converted to an rvalue of
548 // type "pointer to T." The result is a pointer to the
549 // function. (C++ 4.3p1).
550 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000551 } else if (FunctionDecl *Fn
Douglas Gregorcd695e52008-11-10 20:40:00 +0000552 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000553 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000554 SCS.First = ICK_Function_To_Pointer;
555
556 // We were able to resolve the address of the overloaded function,
557 // so we can convert to the type of that function.
558 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000559 if (ToType->isLValueReferenceType())
560 FromType = Context.getLValueReferenceType(FromType);
561 else if (ToType->isRValueReferenceType())
562 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000563 else if (ToType->isMemberPointerType()) {
564 // Resolve address only succeeds if both sides are member pointers,
565 // but it doesn't have to be the same class. See DR 247.
566 // Note that this means that the type of &Derived::fn can be
567 // Ret (Base::*)(Args) if the fn overload actually found is from the
568 // base class, even if it was brought into the derived class via a
569 // using declaration. The standard isn't clear on this issue at all.
570 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
571 FromType = Context.getMemberPointerType(FromType,
572 Context.getTypeDeclType(M->getParent()).getTypePtr());
573 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000574 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000575 } else {
576 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000577 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000578 }
579
580 // The second conversion can be an integral promotion, floating
581 // point promotion, integral conversion, floating point conversion,
582 // floating-integral conversion, pointer conversion,
583 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000584 // For overloading in C, this can also be a "compatible-type"
585 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000586 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000587 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000588 // The unqualified versions of the types are the same: there's no
589 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000590 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000591 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000592 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000593 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000594 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000595 } else if (IsFloatingPointPromotion(FromType, ToType)) {
596 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000597 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000598 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000599 } else if (IsComplexPromotion(FromType, ToType)) {
600 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000601 SCS.Second = ICK_Complex_Promotion;
602 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000603 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000604 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000605 // Integral conversions (C++ 4.7).
606 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000607 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000608 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000609 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
610 // Floating point conversions (C++ 4.8).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000611 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000612 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000613 } else if (FromType->isComplexType() && ToType->isComplexType()) {
614 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000615 SCS.Second = ICK_Complex_Conversion;
616 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000617 } else if ((FromType->isFloatingType() &&
618 ToType->isIntegralType() && (!ToType->isBooleanType() &&
619 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000620 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000621 ToType->isFloatingType())) {
622 // Floating-integral conversions (C++ 4.9).
623 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000624 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000625 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000626 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
627 (ToType->isComplexType() && FromType->isArithmeticType())) {
628 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000629 SCS.Second = ICK_Complex_Real;
630 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000631 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
632 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000633 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000634 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000635 SCS.IncompatibleObjC = IncompatibleObjC;
Mike Stump12b8ce12009-08-04 21:02:39 +0000636 } else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
637 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000638 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000639 } else if (ToType->isBooleanType() &&
640 (FromType->isArithmeticType() ||
641 FromType->isEnumeralType() ||
642 FromType->isPointerType() ||
643 FromType->isBlockPointerType() ||
644 FromType->isMemberPointerType() ||
645 FromType->isNullPtrType())) {
646 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000647 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000648 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000649 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000650 Context.typesAreCompatible(ToType, FromType)) {
651 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000652 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000653 } else {
654 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000655 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000656 }
657
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000658 QualType CanonFrom;
659 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000660 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000661 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000662 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000663 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000664 CanonFrom = Context.getCanonicalType(FromType);
665 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000666 } else {
667 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000668 SCS.Third = ICK_Identity;
669
Mike Stump11289f42009-09-09 15:08:12 +0000670 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000671 // [...] Any difference in top-level cv-qualification is
672 // subsumed by the initialization itself and does not constitute
673 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000674 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000675 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000676 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000677 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
678 FromType = ToType;
679 CanonFrom = CanonTo;
680 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000681 }
682
683 // If we have not converted the argument type to the parameter type,
684 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000685 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000686 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000687
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000688 SCS.ToTypePtr = FromType.getAsOpaquePtr();
689 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000690}
691
692/// IsIntegralPromotion - Determines whether the conversion from the
693/// expression From (whose potentially-adjusted type is FromType) to
694/// ToType is an integral promotion (C++ 4.5). If so, returns true and
695/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000696bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000697 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000698 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000699 if (!To) {
700 return false;
701 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000702
703 // An rvalue of type char, signed char, unsigned char, short int, or
704 // unsigned short int can be converted to an rvalue of type int if
705 // int can represent all the values of the source type; otherwise,
706 // the source rvalue can be converted to an rvalue of type unsigned
707 // int (C++ 4.5p1).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000708 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000709 if (// We can promote any signed, promotable integer type to an int
710 (FromType->isSignedIntegerType() ||
711 // We can promote any unsigned integer type whose size is
712 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000713 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000714 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000715 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000716 }
717
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000718 return To->getKind() == BuiltinType::UInt;
719 }
720
721 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
722 // can be converted to an rvalue of the first of the following types
723 // that can represent all the values of its underlying type: int,
724 // unsigned int, long, or unsigned long (C++ 4.5p2).
725 if ((FromType->isEnumeralType() || FromType->isWideCharType())
726 && ToType->isIntegerType()) {
727 // Determine whether the type we're converting from is signed or
728 // unsigned.
729 bool FromIsSigned;
730 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall9dd450b2009-09-21 23:43:11 +0000731 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000732 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
733 FromIsSigned = UnderlyingType->isSignedIntegerType();
734 } else {
735 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
736 FromIsSigned = true;
737 }
738
739 // The types we'll try to promote to, in the appropriate
740 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000741 QualType PromoteTypes[6] = {
742 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000743 Context.LongTy, Context.UnsignedLongTy ,
744 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000745 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000746 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000747 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
748 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000749 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000750 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
751 // We found the type that we can promote to. If this is the
752 // type we wanted, we have a promotion. Otherwise, no
753 // promotion.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000754 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000755 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
756 }
757 }
758 }
759
760 // An rvalue for an integral bit-field (9.6) can be converted to an
761 // rvalue of type int if int can represent all the values of the
762 // bit-field; otherwise, it can be converted to unsigned int if
763 // unsigned int can represent all the values of the bit-field. If
764 // the bit-field is larger yet, no integral promotion applies to
765 // it. If the bit-field has an enumerated type, it is treated as any
766 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000767 // FIXME: We should delay checking of bit-fields until we actually perform the
768 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000769 using llvm::APSInt;
770 if (From)
771 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000772 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000773 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
774 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
775 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
776 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000777
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000778 // Are we promoting to an int from a bitfield that fits in an int?
779 if (BitWidth < ToSize ||
780 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
781 return To->getKind() == BuiltinType::Int;
782 }
Mike Stump11289f42009-09-09 15:08:12 +0000783
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000784 // Are we promoting to an unsigned int from an unsigned bitfield
785 // that fits into an unsigned int?
786 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
787 return To->getKind() == BuiltinType::UInt;
788 }
Mike Stump11289f42009-09-09 15:08:12 +0000789
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000790 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000791 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000792 }
Mike Stump11289f42009-09-09 15:08:12 +0000793
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000794 // An rvalue of type bool can be converted to an rvalue of type int,
795 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000796 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000797 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000798 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000799
800 return false;
801}
802
803/// IsFloatingPointPromotion - Determines whether the conversion from
804/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
805/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000806bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000807 /// An rvalue of type float can be converted to an rvalue of type
808 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000809 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
810 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000811 if (FromBuiltin->getKind() == BuiltinType::Float &&
812 ToBuiltin->getKind() == BuiltinType::Double)
813 return true;
814
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000815 // C99 6.3.1.5p1:
816 // When a float is promoted to double or long double, or a
817 // double is promoted to long double [...].
818 if (!getLangOptions().CPlusPlus &&
819 (FromBuiltin->getKind() == BuiltinType::Float ||
820 FromBuiltin->getKind() == BuiltinType::Double) &&
821 (ToBuiltin->getKind() == BuiltinType::LongDouble))
822 return true;
823 }
824
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000825 return false;
826}
827
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000828/// \brief Determine if a conversion is a complex promotion.
829///
830/// A complex promotion is defined as a complex -> complex conversion
831/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000832/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000833bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000834 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000835 if (!FromComplex)
836 return false;
837
John McCall9dd450b2009-09-21 23:43:11 +0000838 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000839 if (!ToComplex)
840 return false;
841
842 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000843 ToComplex->getElementType()) ||
844 IsIntegralPromotion(0, FromComplex->getElementType(),
845 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000846}
847
Douglas Gregor237f96c2008-11-26 23:31:11 +0000848/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
849/// the pointer type FromPtr to a pointer to type ToPointee, with the
850/// same type qualifiers as FromPtr has on its pointee type. ToType,
851/// if non-empty, will be a pointer to ToType that may or may not have
852/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000853static QualType
854BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000855 QualType ToPointee, QualType ToType,
856 ASTContext &Context) {
857 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
858 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
859 unsigned Quals = CanonFromPointee.getCVRQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000860
861 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor237f96c2008-11-26 23:31:11 +0000862 if (CanonToPointee.getCVRQualifiers() == Quals) {
863 // ToType is exactly what we need. Return it.
864 if (ToType.getTypePtr())
865 return ToType;
866
867 // Build a pointer to ToPointee. It has the right qualifiers
868 // already.
869 return Context.getPointerType(ToPointee);
870 }
871
872 // Just build a canonical type that has the right qualifiers.
873 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
874}
875
Mike Stump11289f42009-09-09 15:08:12 +0000876static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000877 bool InOverloadResolution,
878 ASTContext &Context) {
879 // Handle value-dependent integral null pointer constants correctly.
880 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
881 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
882 Expr->getType()->isIntegralType())
883 return !InOverloadResolution;
884
885 return Expr->isNullPointerConstant(Context);
886}
Mike Stump11289f42009-09-09 15:08:12 +0000887
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000888/// IsPointerConversion - Determines whether the conversion of the
889/// expression From, which has the (possibly adjusted) type FromType,
890/// can be converted to the type ToType via a pointer conversion (C++
891/// 4.10). If so, returns true and places the converted type (that
892/// might differ from ToType in its cv-qualifiers at some level) into
893/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000894///
Douglas Gregora29dc052008-11-27 01:19:21 +0000895/// This routine also supports conversions to and from block pointers
896/// and conversions with Objective-C's 'id', 'id<protocols...>', and
897/// pointers to interfaces. FIXME: Once we've determined the
898/// appropriate overloading rules for Objective-C, we may want to
899/// split the Objective-C checks into a different routine; however,
900/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000901/// conversions, so for now they live here. IncompatibleObjC will be
902/// set if the conversion is an allowed Objective-C conversion that
903/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000904bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000905 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000906 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +0000907 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +0000908 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +0000909 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
910 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000911
Mike Stump11289f42009-09-09 15:08:12 +0000912 // Conversion from a null pointer constant to any Objective-C pointer type.
913 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000914 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +0000915 ConvertedType = ToType;
916 return true;
917 }
918
Douglas Gregor231d1c62008-11-27 00:15:41 +0000919 // Blocks: Block pointers can be converted to void*.
920 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000921 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000922 ConvertedType = ToType;
923 return true;
924 }
925 // Blocks: A null pointer constant can be converted to a block
926 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +0000927 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000928 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000929 ConvertedType = ToType;
930 return true;
931 }
932
Sebastian Redl576fd422009-05-10 18:38:11 +0000933 // If the left-hand-side is nullptr_t, the right side can be a null
934 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000935 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000936 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +0000937 ConvertedType = ToType;
938 return true;
939 }
940
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000941 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000942 if (!ToTypePtr)
943 return false;
944
945 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +0000946 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000947 ConvertedType = ToType;
948 return true;
949 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000950
Douglas Gregor237f96c2008-11-26 23:31:11 +0000951 // Beyond this point, both types need to be pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000952 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +0000953 if (!FromTypePtr)
954 return false;
955
956 QualType FromPointeeType = FromTypePtr->getPointeeType();
957 QualType ToPointeeType = ToTypePtr->getPointeeType();
958
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000959 // An rvalue of type "pointer to cv T," where T is an object type,
960 // can be converted to an rvalue of type "pointer to cv void" (C++
961 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +0000962 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000963 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +0000964 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000965 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000966 return true;
967 }
968
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000969 // When we're overloading in C, we allow a special kind of pointer
970 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +0000971 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000972 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000973 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000974 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +0000975 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000976 return true;
977 }
978
Douglas Gregor5c407d92008-10-23 00:40:37 +0000979 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +0000980 //
Douglas Gregor5c407d92008-10-23 00:40:37 +0000981 // An rvalue of type "pointer to cv D," where D is a class type,
982 // can be converted to an rvalue of type "pointer to cv B," where
983 // B is a base class (clause 10) of D. If B is an inaccessible
984 // (clause 11) or ambiguous (10.2) base class of D, a program that
985 // necessitates this conversion is ill-formed. The result of the
986 // conversion is a pointer to the base class sub-object of the
987 // derived class object. The null pointer value is converted to
988 // the null pointer value of the destination type.
989 //
Douglas Gregor39c16d42008-10-24 04:54:22 +0000990 // Note that we do not check for ambiguity or inaccessibility
991 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000992 if (getLangOptions().CPlusPlus &&
993 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor237f96c2008-11-26 23:31:11 +0000994 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000995 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +0000996 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000997 ToType, Context);
998 return true;
999 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001000
Douglas Gregora119f102008-12-19 19:13:09 +00001001 return false;
1002}
1003
1004/// isObjCPointerConversion - Determines whether this is an
1005/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1006/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001007bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001008 QualType& ConvertedType,
1009 bool &IncompatibleObjC) {
1010 if (!getLangOptions().ObjC1)
1011 return false;
1012
Steve Naroff7cae42b2009-07-10 23:34:53 +00001013 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001014 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001015 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001016 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001017
Steve Naroff7cae42b2009-07-10 23:34:53 +00001018 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001019 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001020 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001021 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001022 ConvertedType = ToType;
1023 return true;
1024 }
1025 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001026 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001027 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001028 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001029 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001030 ConvertedType = ToType;
1031 return true;
1032 }
1033 // Objective C++: We're able to convert from a pointer to an
1034 // interface to a pointer to a different interface.
1035 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1036 ConvertedType = ToType;
1037 return true;
1038 }
1039
1040 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1041 // Okay: this is some kind of implicit downcast of Objective-C
1042 // interfaces, which is permitted. However, we're going to
1043 // complain about it.
1044 IncompatibleObjC = true;
1045 ConvertedType = FromType;
1046 return true;
1047 }
Mike Stump11289f42009-09-09 15:08:12 +00001048 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001049 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001050 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001051 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001052 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001053 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001054 ToPointeeType = ToBlockPtr->getPointeeType();
1055 else
Douglas Gregora119f102008-12-19 19:13:09 +00001056 return false;
1057
Douglas Gregor033f56d2008-12-23 00:53:59 +00001058 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001059 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001060 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001061 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001062 FromPointeeType = FromBlockPtr->getPointeeType();
1063 else
Douglas Gregora119f102008-12-19 19:13:09 +00001064 return false;
1065
Douglas Gregora119f102008-12-19 19:13:09 +00001066 // If we have pointers to pointers, recursively check whether this
1067 // is an Objective-C conversion.
1068 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1069 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1070 IncompatibleObjC)) {
1071 // We always complain about this conversion.
1072 IncompatibleObjC = true;
1073 ConvertedType = ToType;
1074 return true;
1075 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001076 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001077 // differences in the argument and result types are in Objective-C
1078 // pointer conversions. If so, we permit the conversion (but
1079 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001080 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001081 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001082 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001083 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001084 if (FromFunctionType && ToFunctionType) {
1085 // If the function types are exactly the same, this isn't an
1086 // Objective-C pointer conversion.
1087 if (Context.getCanonicalType(FromPointeeType)
1088 == Context.getCanonicalType(ToPointeeType))
1089 return false;
1090
1091 // Perform the quick checks that will tell us whether these
1092 // function types are obviously different.
1093 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1094 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1095 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1096 return false;
1097
1098 bool HasObjCConversion = false;
1099 if (Context.getCanonicalType(FromFunctionType->getResultType())
1100 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1101 // Okay, the types match exactly. Nothing to do.
1102 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1103 ToFunctionType->getResultType(),
1104 ConvertedType, IncompatibleObjC)) {
1105 // Okay, we have an Objective-C pointer conversion.
1106 HasObjCConversion = true;
1107 } else {
1108 // Function types are too different. Abort.
1109 return false;
1110 }
Mike Stump11289f42009-09-09 15:08:12 +00001111
Douglas Gregora119f102008-12-19 19:13:09 +00001112 // Check argument types.
1113 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1114 ArgIdx != NumArgs; ++ArgIdx) {
1115 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1116 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1117 if (Context.getCanonicalType(FromArgType)
1118 == Context.getCanonicalType(ToArgType)) {
1119 // Okay, the types match exactly. Nothing to do.
1120 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1121 ConvertedType, IncompatibleObjC)) {
1122 // Okay, we have an Objective-C pointer conversion.
1123 HasObjCConversion = true;
1124 } else {
1125 // Argument types are too different. Abort.
1126 return false;
1127 }
1128 }
1129
1130 if (HasObjCConversion) {
1131 // We had an Objective-C conversion. Allow this pointer
1132 // conversion, but complain about it.
1133 ConvertedType = ToType;
1134 IncompatibleObjC = true;
1135 return true;
1136 }
1137 }
1138
Sebastian Redl72b597d2009-01-25 19:43:20 +00001139 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001140}
1141
Douglas Gregor39c16d42008-10-24 04:54:22 +00001142/// CheckPointerConversion - Check the pointer conversion from the
1143/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001144/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001145/// conversions for which IsPointerConversion has already returned
1146/// true. It returns true and produces a diagnostic if there was an
1147/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001148bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
1149 CastExpr::CastKind &Kind) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001150 QualType FromType = From->getType();
1151
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001152 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1153 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001154 QualType FromPointeeType = FromPtrType->getPointeeType(),
1155 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001156
Douglas Gregor39c16d42008-10-24 04:54:22 +00001157 if (FromPointeeType->isRecordType() &&
1158 ToPointeeType->isRecordType()) {
1159 // We must have a derived-to-base conversion. Check an
1160 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001161 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1162 From->getExprLoc(),
1163 From->getSourceRange()))
1164 return true;
1165
1166 // The conversion was successful.
1167 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001168 }
1169 }
Mike Stump11289f42009-09-09 15:08:12 +00001170 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001171 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001172 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001173 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001174 // Objective-C++ conversions are always okay.
1175 // FIXME: We should have a different class of conversions for the
1176 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001177 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001178 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001179
Steve Naroff7cae42b2009-07-10 23:34:53 +00001180 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001181 return false;
1182}
1183
Sebastian Redl72b597d2009-01-25 19:43:20 +00001184/// IsMemberPointerConversion - Determines whether the conversion of the
1185/// expression From, which has the (possibly adjusted) type FromType, can be
1186/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1187/// If so, returns true and places the converted type (that might differ from
1188/// ToType in its cv-qualifiers at some level) into ConvertedType.
1189bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Mike Stump11289f42009-09-09 15:08:12 +00001190 QualType ToType, QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001191 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001192 if (!ToTypePtr)
1193 return false;
1194
1195 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1196 if (From->isNullPointerConstant(Context)) {
1197 ConvertedType = ToType;
1198 return true;
1199 }
1200
1201 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001202 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001203 if (!FromTypePtr)
1204 return false;
1205
1206 // A pointer to member of B can be converted to a pointer to member of D,
1207 // where D is derived from B (C++ 4.11p2).
1208 QualType FromClass(FromTypePtr->getClass(), 0);
1209 QualType ToClass(ToTypePtr->getClass(), 0);
1210 // FIXME: What happens when these are dependent? Is this function even called?
1211
1212 if (IsDerivedFrom(ToClass, FromClass)) {
1213 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1214 ToClass.getTypePtr());
1215 return true;
1216 }
1217
1218 return false;
1219}
1220
1221/// CheckMemberPointerConversion - Check the member pointer conversion from the
1222/// expression From to the type ToType. This routine checks for ambiguous or
1223/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1224/// for which IsMemberPointerConversion has already returned true. It returns
1225/// true and produces a diagnostic if there was an error, or returns false
1226/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001227bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Anders Carlssond7923c62009-08-22 23:33:40 +00001228 CastExpr::CastKind &Kind) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001229 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001230 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001231 if (!FromPtrType) {
1232 // This must be a null pointer to member pointer conversion
Mike Stump11289f42009-09-09 15:08:12 +00001233 assert(From->isNullPointerConstant(Context) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001234 "Expr must be null pointer constant!");
1235 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001236 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001237 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001238
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001239 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001240 assert(ToPtrType && "No member pointer cast has a target type "
1241 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001242
Sebastian Redled8f2002009-01-28 18:33:18 +00001243 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1244 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001245
Sebastian Redled8f2002009-01-28 18:33:18 +00001246 // FIXME: What about dependent types?
1247 assert(FromClass->isRecordType() && "Pointer into non-class.");
1248 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001249
Sebastian Redled8f2002009-01-28 18:33:18 +00001250 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1251 /*DetectVirtual=*/true);
1252 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1253 assert(DerivationOkay &&
1254 "Should not have been called if derivation isn't OK.");
1255 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001256
Sebastian Redled8f2002009-01-28 18:33:18 +00001257 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1258 getUnqualifiedType())) {
1259 // Derivation is ambiguous. Redo the check to find the exact paths.
1260 Paths.clear();
1261 Paths.setRecordingPaths(true);
1262 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1263 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1264 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001265
Sebastian Redled8f2002009-01-28 18:33:18 +00001266 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1267 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1268 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1269 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001270 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001271
Douglas Gregor89ee6822009-02-28 01:32:25 +00001272 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001273 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1274 << FromClass << ToClass << QualType(VBase, 0)
1275 << From->getSourceRange();
1276 return true;
1277 }
1278
Anders Carlssond7923c62009-08-22 23:33:40 +00001279 // Must be a base to derived member conversion.
1280 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001281 return false;
1282}
1283
Douglas Gregor9a657932008-10-21 23:43:52 +00001284/// IsQualificationConversion - Determines whether the conversion from
1285/// an rvalue of type FromType to ToType is a qualification conversion
1286/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001287bool
1288Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001289 FromType = Context.getCanonicalType(FromType);
1290 ToType = Context.getCanonicalType(ToType);
1291
1292 // If FromType and ToType are the same type, this is not a
1293 // qualification conversion.
1294 if (FromType == ToType)
1295 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001296
Douglas Gregor9a657932008-10-21 23:43:52 +00001297 // (C++ 4.4p4):
1298 // A conversion can add cv-qualifiers at levels other than the first
1299 // in multi-level pointers, subject to the following rules: [...]
1300 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001301 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001302 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001303 // Within each iteration of the loop, we check the qualifiers to
1304 // determine if this still looks like a qualification
1305 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001306 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001307 // until there are no more pointers or pointers-to-members left to
1308 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001309 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001310
1311 // -- for every j > 0, if const is in cv 1,j then const is in cv
1312 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001313 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001314 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001315
Douglas Gregor9a657932008-10-21 23:43:52 +00001316 // -- if the cv 1,j and cv 2,j are different, then const is in
1317 // every cv for 0 < k < j.
1318 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001319 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001320 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001321
Douglas Gregor9a657932008-10-21 23:43:52 +00001322 // Keep track of whether all prior cv-qualifiers in the "to" type
1323 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001324 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001325 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001326 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001327
1328 // We are left with FromType and ToType being the pointee types
1329 // after unwrapping the original FromType and ToType the same number
1330 // of types. If we unwrapped any pointers, and if FromType and
1331 // ToType have the same unqualified type (since we checked
1332 // qualifiers above), then this is a qualification conversion.
1333 return UnwrappedAnyPointer &&
1334 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1335}
1336
Douglas Gregor05155d82009-08-21 23:19:43 +00001337/// \brief Given a function template or function, extract the function template
1338/// declaration (if any) and the underlying function declaration.
1339template<typename T>
1340static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1341 FunctionTemplateDecl *&FunctionTemplate) {
1342 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1343 if (FunctionTemplate)
1344 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1345 else
1346 Function = cast<T>(Orig);
1347}
1348
Douglas Gregor576e98c2009-01-30 23:27:23 +00001349/// Determines whether there is a user-defined conversion sequence
1350/// (C++ [over.ics.user]) that converts expression From to the type
1351/// ToType. If such a conversion exists, User will contain the
1352/// user-defined conversion sequence that performs such a conversion
1353/// and this routine will return true. Otherwise, this routine returns
1354/// false and User is unspecified.
1355///
1356/// \param AllowConversionFunctions true if the conversion should
1357/// consider conversion functions at all. If false, only constructors
1358/// will be considered.
1359///
1360/// \param AllowExplicit true if the conversion should consider C++0x
1361/// "explicit" conversion functions as well as non-explicit conversion
1362/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001363///
1364/// \param ForceRValue true if the expression should be treated as an rvalue
1365/// for overload resolution.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001366Sema::OverloadingResult Sema::IsUserDefinedConversion(
1367 Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001368 UserDefinedConversionSequence& User,
Fariborz Jahanian19c73282009-09-15 00:10:11 +00001369 OverloadCandidateSet& CandidateSet,
Douglas Gregor576e98c2009-01-30 23:27:23 +00001370 bool AllowConversionFunctions,
Mike Stump11289f42009-09-09 15:08:12 +00001371 bool AllowExplicit, bool ForceRValue) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001372 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001373 if (CXXRecordDecl *ToRecordDecl
Douglas Gregor89ee6822009-02-28 01:32:25 +00001374 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1375 // C++ [over.match.ctor]p1:
1376 // When objects of class type are direct-initialized (8.5), or
1377 // copy-initialized from an expression of the same or a
1378 // derived class type (8.5), overload resolution selects the
1379 // constructor. [...] For copy-initialization, the candidate
1380 // functions are all the converting constructors (12.3.1) of
1381 // that class. The argument list is the expression-list within
1382 // the parentheses of the initializer.
Mike Stump11289f42009-09-09 15:08:12 +00001383 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001384 = Context.DeclarationNames.getCXXConstructorName(
1385 Context.getCanonicalType(ToType).getUnqualifiedType());
1386 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001387 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001388 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001389 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001390 // Find the constructor (which may be a template).
1391 CXXConstructorDecl *Constructor = 0;
1392 FunctionTemplateDecl *ConstructorTmpl
1393 = dyn_cast<FunctionTemplateDecl>(*Con);
1394 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001395 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001396 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1397 else
1398 Constructor = cast<CXXConstructorDecl>(*Con);
Mike Stump11289f42009-09-09 15:08:12 +00001399
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001400 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001401 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001402 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001403 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001404 1, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00001405 /*SuppressUserConversions=*/true,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001406 ForceRValue);
1407 else
1408 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1409 /*SuppressUserConversions=*/true, ForceRValue);
1410 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001411 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001412 }
1413 }
1414
Douglas Gregor576e98c2009-01-30 23:27:23 +00001415 if (!AllowConversionFunctions) {
1416 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001417 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1418 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001419 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001420 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001421 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001422 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001423 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001424 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1425 // Add all of the conversion functions as candidates.
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001426 OverloadedFunctionDecl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001427 = FromRecordDecl->getVisibleConversionFunctions();
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001428 for (OverloadedFunctionDecl::function_iterator Func
1429 = Conversions->function_begin();
1430 Func != Conversions->function_end(); ++Func) {
1431 CXXConversionDecl *Conv;
1432 FunctionTemplateDecl *ConvTemplate;
1433 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1434 if (ConvTemplate)
1435 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1436 else
1437 Conv = dyn_cast<CXXConversionDecl>(*Func);
1438
1439 if (AllowExplicit || !Conv->isExplicit()) {
1440 if (ConvTemplate)
1441 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1442 CandidateSet);
1443 else
1444 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1445 }
1446 }
1447 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001448 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001449
1450 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001451 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001452 case OR_Success:
1453 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001454 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001455 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1456 // C++ [over.ics.user]p1:
1457 // If the user-defined conversion is specified by a
1458 // constructor (12.3.1), the initial standard conversion
1459 // sequence converts the source type to the type required by
1460 // the argument of the constructor.
1461 //
1462 // FIXME: What about ellipsis conversions?
1463 QualType ThisType = Constructor->getThisType(Context);
1464 User.Before = Best->Conversions[0].Standard;
1465 User.ConversionFunction = Constructor;
1466 User.After.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00001467 User.After.FromTypePtr
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001468 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001469 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001470 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001471 } else if (CXXConversionDecl *Conversion
1472 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1473 // C++ [over.ics.user]p1:
1474 //
1475 // [...] If the user-defined conversion is specified by a
1476 // conversion function (12.3.2), the initial standard
1477 // conversion sequence converts the source type to the
1478 // implicit object parameter of the conversion function.
1479 User.Before = Best->Conversions[0].Standard;
1480 User.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00001481
1482 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001483 // The second standard conversion sequence converts the
1484 // result of the user-defined conversion to the target type
1485 // for the sequence. Since an implicit conversion sequence
1486 // is an initialization, the special rules for
1487 // initialization by user-defined conversion apply when
1488 // selecting the best user-defined conversion for a
1489 // user-defined conversion sequence (see 13.3.3 and
1490 // 13.3.3.1).
1491 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001492 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001493 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001494 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001495 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001496 }
Mike Stump11289f42009-09-09 15:08:12 +00001497
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001498 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001499 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001500 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001501 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001502 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001503
1504 case OR_Ambiguous:
1505 // FIXME: See C++ [over.best.ics]p10 for the handling of
1506 // ambiguous conversion sequences.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001507 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001508 }
1509
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001510 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001511}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001512
1513bool
1514Sema::DiagnoseAmbiguousUserDefinedConversion(Expr *From, QualType ToType) {
1515 ImplicitConversionSequence ICS;
1516 OverloadCandidateSet CandidateSet;
1517 OverloadingResult OvResult =
1518 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1519 CandidateSet, true, false, false);
1520 if (OvResult != OR_Ambiguous)
1521 return false;
1522 Diag(From->getSourceRange().getBegin(),
1523 diag::err_typecheck_ambiguous_condition)
1524 << From->getType() << ToType << From->getSourceRange();
1525 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1526 return true;
1527}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001528
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001529/// CompareImplicitConversionSequences - Compare two implicit
1530/// conversion sequences to determine whether one is better than the
1531/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001532ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001533Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1534 const ImplicitConversionSequence& ICS2)
1535{
1536 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1537 // conversion sequences (as defined in 13.3.3.1)
1538 // -- a standard conversion sequence (13.3.3.1.1) is a better
1539 // conversion sequence than a user-defined conversion sequence or
1540 // an ellipsis conversion sequence, and
1541 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1542 // conversion sequence than an ellipsis conversion sequence
1543 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001544 //
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001545 if (ICS1.ConversionKind < ICS2.ConversionKind)
1546 return ImplicitConversionSequence::Better;
1547 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1548 return ImplicitConversionSequence::Worse;
1549
1550 // Two implicit conversion sequences of the same form are
1551 // indistinguishable conversion sequences unless one of the
1552 // following rules apply: (C++ 13.3.3.2p3):
1553 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1554 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump11289f42009-09-09 15:08:12 +00001555 else if (ICS1.ConversionKind ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001556 ImplicitConversionSequence::UserDefinedConversion) {
1557 // User-defined conversion sequence U1 is a better conversion
1558 // sequence than another user-defined conversion sequence U2 if
1559 // they contain the same user-defined conversion function or
1560 // constructor and if the second standard conversion sequence of
1561 // U1 is better than the second standard conversion sequence of
1562 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001563 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001564 ICS2.UserDefined.ConversionFunction)
1565 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1566 ICS2.UserDefined.After);
1567 }
1568
1569 return ImplicitConversionSequence::Indistinguishable;
1570}
1571
1572/// CompareStandardConversionSequences - Compare two standard
1573/// conversion sequences to determine whether one is better than the
1574/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001575ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001576Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1577 const StandardConversionSequence& SCS2)
1578{
1579 // Standard conversion sequence S1 is a better conversion sequence
1580 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1581
1582 // -- S1 is a proper subsequence of S2 (comparing the conversion
1583 // sequences in the canonical form defined by 13.3.3.1.1,
1584 // excluding any Lvalue Transformation; the identity conversion
1585 // sequence is considered to be a subsequence of any
1586 // non-identity conversion sequence) or, if not that,
1587 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1588 // Neither is a proper subsequence of the other. Do nothing.
1589 ;
1590 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1591 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001592 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001593 SCS1.Third == ICK_Identity))
1594 // SCS1 is a proper subsequence of SCS2.
1595 return ImplicitConversionSequence::Better;
1596 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1597 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001598 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001599 SCS2.Third == ICK_Identity))
1600 // SCS2 is a proper subsequence of SCS1.
1601 return ImplicitConversionSequence::Worse;
1602
1603 // -- the rank of S1 is better than the rank of S2 (by the rules
1604 // defined below), or, if not that,
1605 ImplicitConversionRank Rank1 = SCS1.getRank();
1606 ImplicitConversionRank Rank2 = SCS2.getRank();
1607 if (Rank1 < Rank2)
1608 return ImplicitConversionSequence::Better;
1609 else if (Rank2 < Rank1)
1610 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001611
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001612 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1613 // are indistinguishable unless one of the following rules
1614 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001615
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001616 // A conversion that is not a conversion of a pointer, or
1617 // pointer to member, to bool is better than another conversion
1618 // that is such a conversion.
1619 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1620 return SCS2.isPointerConversionToBool()
1621 ? ImplicitConversionSequence::Better
1622 : ImplicitConversionSequence::Worse;
1623
Douglas Gregor5c407d92008-10-23 00:40:37 +00001624 // C++ [over.ics.rank]p4b2:
1625 //
1626 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001627 // conversion of B* to A* is better than conversion of B* to
1628 // void*, and conversion of A* to void* is better than conversion
1629 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001630 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001631 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001632 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001633 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001634 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1635 // Exactly one of the conversion sequences is a conversion to
1636 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001637 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1638 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001639 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1640 // Neither conversion sequence converts to a void pointer; compare
1641 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001642 if (ImplicitConversionSequence::CompareKind DerivedCK
1643 = CompareDerivedToBaseConversions(SCS1, SCS2))
1644 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001645 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1646 // Both conversion sequences are conversions to void
1647 // pointers. Compare the source types to determine if there's an
1648 // inheritance relationship in their sources.
1649 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1650 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1651
1652 // Adjust the types we're converting from via the array-to-pointer
1653 // conversion, if we need to.
1654 if (SCS1.First == ICK_Array_To_Pointer)
1655 FromType1 = Context.getArrayDecayedType(FromType1);
1656 if (SCS2.First == ICK_Array_To_Pointer)
1657 FromType2 = Context.getArrayDecayedType(FromType2);
1658
Mike Stump11289f42009-09-09 15:08:12 +00001659 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001660 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001661 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001662 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001663
1664 if (IsDerivedFrom(FromPointee2, FromPointee1))
1665 return ImplicitConversionSequence::Better;
1666 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1667 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001668
1669 // Objective-C++: If one interface is more specific than the
1670 // other, it is the better one.
John McCall9dd450b2009-09-21 23:43:11 +00001671 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1672 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001673 if (FromIface1 && FromIface1) {
1674 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1675 return ImplicitConversionSequence::Better;
1676 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1677 return ImplicitConversionSequence::Worse;
1678 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001679 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001680
1681 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1682 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001683 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001684 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001685 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001686
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001687 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001688 // C++0x [over.ics.rank]p3b4:
1689 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1690 // implicit object parameter of a non-static member function declared
1691 // without a ref-qualifier, and S1 binds an rvalue reference to an
1692 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001693 // FIXME: We don't know if we're dealing with the implicit object parameter,
1694 // or if the member function in this case has a ref qualifier.
1695 // (Of course, we don't have ref qualifiers yet.)
1696 if (SCS1.RRefBinding != SCS2.RRefBinding)
1697 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1698 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001699
1700 // C++ [over.ics.rank]p3b4:
1701 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1702 // which the references refer are the same type except for
1703 // top-level cv-qualifiers, and the type to which the reference
1704 // initialized by S2 refers is more cv-qualified than the type
1705 // to which the reference initialized by S1 refers.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001706 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1707 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001708 T1 = Context.getCanonicalType(T1);
1709 T2 = Context.getCanonicalType(T2);
1710 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1711 if (T2.isMoreQualifiedThan(T1))
1712 return ImplicitConversionSequence::Better;
1713 else if (T1.isMoreQualifiedThan(T2))
1714 return ImplicitConversionSequence::Worse;
1715 }
1716 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001717
1718 return ImplicitConversionSequence::Indistinguishable;
1719}
1720
1721/// CompareQualificationConversions - Compares two standard conversion
1722/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001723/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1724ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001725Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001726 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001727 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001728 // -- S1 and S2 differ only in their qualification conversion and
1729 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1730 // cv-qualification signature of type T1 is a proper subset of
1731 // the cv-qualification signature of type T2, and S1 is not the
1732 // deprecated string literal array-to-pointer conversion (4.2).
1733 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1734 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1735 return ImplicitConversionSequence::Indistinguishable;
1736
1737 // FIXME: the example in the standard doesn't use a qualification
1738 // conversion (!)
1739 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1740 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1741 T1 = Context.getCanonicalType(T1);
1742 T2 = Context.getCanonicalType(T2);
1743
1744 // If the types are the same, we won't learn anything by unwrapped
1745 // them.
1746 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1747 return ImplicitConversionSequence::Indistinguishable;
1748
Mike Stump11289f42009-09-09 15:08:12 +00001749 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001750 = ImplicitConversionSequence::Indistinguishable;
1751 while (UnwrapSimilarPointerTypes(T1, T2)) {
1752 // Within each iteration of the loop, we check the qualifiers to
1753 // determine if this still looks like a qualification
1754 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001755 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001756 // until there are no more pointers or pointers-to-members left
1757 // to unwrap. This essentially mimics what
1758 // IsQualificationConversion does, but here we're checking for a
1759 // strict subset of qualifiers.
1760 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1761 // The qualifiers are the same, so this doesn't tell us anything
1762 // about how the sequences rank.
1763 ;
1764 else if (T2.isMoreQualifiedThan(T1)) {
1765 // T1 has fewer qualifiers, so it could be the better sequence.
1766 if (Result == ImplicitConversionSequence::Worse)
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::Better;
1772 } else if (T1.isMoreQualifiedThan(T2)) {
1773 // T2 has fewer qualifiers, so it could be the better sequence.
1774 if (Result == ImplicitConversionSequence::Better)
1775 // Neither has qualifiers that are a subset of the other's
1776 // qualifiers.
1777 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001778
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001779 Result = ImplicitConversionSequence::Worse;
1780 } else {
1781 // Qualifiers are disjoint.
1782 return ImplicitConversionSequence::Indistinguishable;
1783 }
1784
1785 // If the types after this point are equivalent, we're done.
1786 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1787 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001788 }
1789
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001790 // Check that the winning standard conversion sequence isn't using
1791 // the deprecated string literal array to pointer conversion.
1792 switch (Result) {
1793 case ImplicitConversionSequence::Better:
1794 if (SCS1.Deprecated)
1795 Result = ImplicitConversionSequence::Indistinguishable;
1796 break;
1797
1798 case ImplicitConversionSequence::Indistinguishable:
1799 break;
1800
1801 case ImplicitConversionSequence::Worse:
1802 if (SCS2.Deprecated)
1803 Result = ImplicitConversionSequence::Indistinguishable;
1804 break;
1805 }
1806
1807 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001808}
1809
Douglas Gregor5c407d92008-10-23 00:40:37 +00001810/// CompareDerivedToBaseConversions - Compares two standard conversion
1811/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001812/// various kinds of derived-to-base conversions (C++
1813/// [over.ics.rank]p4b3). As part of these checks, we also look at
1814/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001815ImplicitConversionSequence::CompareKind
1816Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1817 const StandardConversionSequence& SCS2) {
1818 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1819 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1820 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1821 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1822
1823 // Adjust the types we're converting from via the array-to-pointer
1824 // conversion, if we need to.
1825 if (SCS1.First == ICK_Array_To_Pointer)
1826 FromType1 = Context.getArrayDecayedType(FromType1);
1827 if (SCS2.First == ICK_Array_To_Pointer)
1828 FromType2 = Context.getArrayDecayedType(FromType2);
1829
1830 // Canonicalize all of the types.
1831 FromType1 = Context.getCanonicalType(FromType1);
1832 ToType1 = Context.getCanonicalType(ToType1);
1833 FromType2 = Context.getCanonicalType(FromType2);
1834 ToType2 = Context.getCanonicalType(ToType2);
1835
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001836 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001837 //
1838 // If class B is derived directly or indirectly from class A and
1839 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001840 //
1841 // For Objective-C, we let A, B, and C also be Objective-C
1842 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001843
1844 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00001845 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00001846 SCS2.Second == ICK_Pointer_Conversion &&
1847 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1848 FromType1->isPointerType() && FromType2->isPointerType() &&
1849 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001850 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001851 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001852 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001853 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001854 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001855 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001856 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001857 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001858
John McCall9dd450b2009-09-21 23:43:11 +00001859 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1860 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1861 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1862 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001863
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001864 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00001865 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1866 if (IsDerivedFrom(ToPointee1, ToPointee2))
1867 return ImplicitConversionSequence::Better;
1868 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1869 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001870
1871 if (ToIface1 && ToIface2) {
1872 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1873 return ImplicitConversionSequence::Better;
1874 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1875 return ImplicitConversionSequence::Worse;
1876 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001877 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001878
1879 // -- conversion of B* to A* is better than conversion of C* to A*,
1880 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1881 if (IsDerivedFrom(FromPointee2, FromPointee1))
1882 return ImplicitConversionSequence::Better;
1883 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1884 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00001885
Douglas Gregor237f96c2008-11-26 23:31:11 +00001886 if (FromIface1 && FromIface2) {
1887 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1888 return ImplicitConversionSequence::Better;
1889 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1890 return ImplicitConversionSequence::Worse;
1891 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001892 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001893 }
1894
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001895 // Compare based on reference bindings.
1896 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1897 SCS1.Second == ICK_Derived_To_Base) {
1898 // -- binding of an expression of type C to a reference of type
1899 // B& is better than binding an expression of type C to a
1900 // reference of type A&,
1901 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1902 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1903 if (IsDerivedFrom(ToType1, ToType2))
1904 return ImplicitConversionSequence::Better;
1905 else if (IsDerivedFrom(ToType2, ToType1))
1906 return ImplicitConversionSequence::Worse;
1907 }
1908
Douglas Gregor2fe98832008-11-03 19:09:14 +00001909 // -- binding of an expression of type B to a reference of type
1910 // A& is better than binding an expression of type C to a
1911 // reference of type A&,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001912 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1913 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1914 if (IsDerivedFrom(FromType2, FromType1))
1915 return ImplicitConversionSequence::Better;
1916 else if (IsDerivedFrom(FromType1, FromType2))
1917 return ImplicitConversionSequence::Worse;
1918 }
1919 }
1920
1921
1922 // FIXME: conversion of A::* to B::* is better than conversion of
1923 // A::* to C::*,
1924
1925 // FIXME: conversion of B::* to C::* is better than conversion of
1926 // A::* to C::*, and
1927
Douglas Gregor2fe98832008-11-03 19:09:14 +00001928 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1929 SCS1.Second == ICK_Derived_To_Base) {
1930 // -- conversion of C to B is better than conversion of C to A,
1931 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1932 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1933 if (IsDerivedFrom(ToType1, ToType2))
1934 return ImplicitConversionSequence::Better;
1935 else if (IsDerivedFrom(ToType2, ToType1))
1936 return ImplicitConversionSequence::Worse;
1937 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001938
Douglas Gregor2fe98832008-11-03 19:09:14 +00001939 // -- conversion of B to A is better than conversion of C to A.
1940 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1941 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1942 if (IsDerivedFrom(FromType2, FromType1))
1943 return ImplicitConversionSequence::Better;
1944 else if (IsDerivedFrom(FromType1, FromType2))
1945 return ImplicitConversionSequence::Worse;
1946 }
1947 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001948
Douglas Gregor5c407d92008-10-23 00:40:37 +00001949 return ImplicitConversionSequence::Indistinguishable;
1950}
1951
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001952/// TryCopyInitialization - Try to copy-initialize a value of type
1953/// ToType from the expression From. Return the implicit conversion
1954/// sequence required to pass this argument, which may be a bad
1955/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00001956/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00001957/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1958/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00001959ImplicitConversionSequence
1960Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00001961 bool SuppressUserConversions, bool ForceRValue,
1962 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001963 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001964 ImplicitConversionSequence ICS;
Mike Stump11289f42009-09-09 15:08:12 +00001965 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00001966 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00001967 SuppressUserConversions,
1968 /*AllowExplicit=*/false,
1969 ForceRValue,
1970 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001971 return ICS;
1972 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001973 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00001974 SuppressUserConversions,
1975 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001976 ForceRValue,
1977 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001978 }
1979}
1980
Sebastian Redl42e92c42009-04-12 17:16:29 +00001981/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1982/// the expression @p From. Returns true (and emits a diagnostic) if there was
1983/// an error, returns false if the initialization succeeded. Elidable should
1984/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1985/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00001986bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redl42e92c42009-04-12 17:16:29 +00001987 const char* Flavor, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001988 if (!getLangOptions().CPlusPlus) {
1989 // In C, argument passing is the same as performing an assignment.
1990 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001991
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001992 AssignConvertType ConvTy =
1993 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00001994 if (ConvTy != Compatible &&
1995 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1996 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00001997
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001998 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1999 FromType, From, Flavor);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002000 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002001
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002002 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002003 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002004 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002005 /*SuppressUserConversions=*/false,
2006 /*AllowExplicit=*/false,
2007 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002008
Sebastian Redl42e92c42009-04-12 17:16:29 +00002009 if (!PerformImplicitConversion(From, ToType, Flavor,
2010 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002011 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002012 if (!DiagnoseAmbiguousUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002013 return Diag(From->getSourceRange().getBegin(),
2014 diag::err_typecheck_convert_incompatible)
2015 << ToType << From->getType() << Flavor << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002016 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002017}
2018
Douglas Gregor436424c2008-11-18 23:14:02 +00002019/// TryObjectArgumentInitialization - Try to initialize the object
2020/// parameter of the given member function (@c Method) from the
2021/// expression @p From.
2022ImplicitConversionSequence
2023Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
2024 QualType ClassType = Context.getTypeDeclType(Method->getParent());
2025 unsigned MethodQuals = Method->getTypeQualifiers();
2026 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
2027
2028 // Set up the conversion sequence as a "bad" conversion, to allow us
2029 // to exit early.
2030 ImplicitConversionSequence ICS;
2031 ICS.Standard.setAsIdentityConversion();
2032 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2033
2034 // We need to have an object of class type.
2035 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002036 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002037 FromType = PT->getPointeeType();
2038
2039 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002040
2041 // The implicit object parmeter is has the type "reference to cv X",
2042 // where X is the class of which the function is a member
2043 // (C++ [over.match.funcs]p4). However, when finding an implicit
2044 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002045 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002046 // (C++ [over.match.funcs]p5). We perform a simplified version of
2047 // reference binding here, that allows class rvalues to bind to
2048 // non-constant references.
2049
2050 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2051 // with the implicit object parameter (C++ [over.match.funcs]p5).
2052 QualType FromTypeCanon = Context.getCanonicalType(FromType);
2053 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2054 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2055 return ICS;
2056
2057 // Check that we have either the same type or a derived type. It
2058 // affects the conversion rank.
2059 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2060 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2061 ICS.Standard.Second = ICK_Identity;
2062 else if (IsDerivedFrom(FromType, ClassType))
2063 ICS.Standard.Second = ICK_Derived_To_Base;
2064 else
2065 return ICS;
2066
2067 // Success. Mark this as a reference binding.
2068 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2069 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2070 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2071 ICS.Standard.ReferenceBinding = true;
2072 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002073 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002074 return ICS;
2075}
2076
2077/// PerformObjectArgumentInitialization - Perform initialization of
2078/// the implicit object parameter for the given Method with the given
2079/// expression.
2080bool
2081Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002082 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002083 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002084 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002085
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002086 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002087 FromRecordType = PT->getPointeeType();
2088 DestType = Method->getThisType(Context);
2089 } else {
2090 FromRecordType = From->getType();
2091 DestType = ImplicitParamRecordType;
2092 }
2093
Mike Stump11289f42009-09-09 15:08:12 +00002094 ImplicitConversionSequence ICS
Douglas Gregor436424c2008-11-18 23:14:02 +00002095 = TryObjectArgumentInitialization(From, Method);
2096 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2097 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002098 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002099 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002100
Douglas Gregor436424c2008-11-18 23:14:02 +00002101 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002102 CheckDerivedToBaseConversion(FromRecordType,
2103 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002104 From->getSourceRange().getBegin(),
2105 From->getSourceRange()))
2106 return true;
2107
Mike Stump11289f42009-09-09 15:08:12 +00002108 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002109 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002110 return false;
2111}
2112
Douglas Gregor5fb53972009-01-14 15:45:31 +00002113/// TryContextuallyConvertToBool - Attempt to contextually convert the
2114/// expression From to bool (C++0x [conv]p3).
2115ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002116 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002117 // FIXME: Are these flags correct?
2118 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002119 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002120 /*ForceRValue=*/false,
2121 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002122}
2123
2124/// PerformContextuallyConvertToBool - Perform a contextual conversion
2125/// of the expression From to bool (C++0x [conv]p3).
2126bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2127 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2128 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2129 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002130
2131 if (!DiagnoseAmbiguousUserDefinedConversion(From, Context.BoolTy))
2132 return Diag(From->getSourceRange().getBegin(),
2133 diag::err_typecheck_bool_condition)
2134 << From->getType() << From->getSourceRange();
2135 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002136}
2137
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002138/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002139/// candidate functions, using the given function call arguments. If
2140/// @p SuppressUserConversions, then don't allow user-defined
2141/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002142/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2143/// hacky way to implement the overloading rules for elidable copy
2144/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002145///
2146/// \para PartialOverloading true if we are performing "partial" overloading
2147/// based on an incomplete set of function arguments. This feature is used by
2148/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002149void
2150Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002151 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002152 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002153 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002154 bool ForceRValue,
2155 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002156 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002157 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002158 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002159 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002160 "Use AddConversionCandidate for conversion functions");
Mike Stump11289f42009-09-09 15:08:12 +00002161 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002162 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002163
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002164 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002165 if (!isa<CXXConstructorDecl>(Method)) {
2166 // If we get here, it's because we're calling a member function
2167 // that is named without a member access expression (e.g.,
2168 // "this->f") that was either written explicitly or created
2169 // implicitly. This can happen with a qualified call to a member
2170 // function, e.g., X::f(). We use a NULL object as the implied
2171 // object argument (C++ [over.call.func]p3).
Mike Stump11289f42009-09-09 15:08:12 +00002172 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002173 SuppressUserConversions, ForceRValue);
2174 return;
2175 }
2176 // We treat a constructor like a non-member function, since its object
2177 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002178 }
2179
2180
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002181 // Add this candidate
2182 CandidateSet.push_back(OverloadCandidate());
2183 OverloadCandidate& Candidate = CandidateSet.back();
2184 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002185 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002186 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002187 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002188
2189 unsigned NumArgsInProto = Proto->getNumArgs();
2190
2191 // (C++ 13.3.2p2): A candidate function having fewer than m
2192 // parameters is viable only if it has an ellipsis in its parameter
2193 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002194 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2195 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002196 Candidate.Viable = false;
2197 return;
2198 }
2199
2200 // (C++ 13.3.2p2): A candidate function having more than m parameters
2201 // is viable only if the (m+1)st parameter has a default argument
2202 // (8.3.6). For the purposes of overload resolution, the
2203 // parameter list is truncated on the right, so that there are
2204 // exactly m parameters.
2205 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002206 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002207 // Not enough arguments.
2208 Candidate.Viable = false;
2209 return;
2210 }
2211
2212 // Determine the implicit conversion sequences for each of the
2213 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002214 Candidate.Conversions.resize(NumArgs);
2215 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2216 if (ArgIdx < NumArgsInProto) {
2217 // (C++ 13.3.2p3): for F to be a viable function, there shall
2218 // exist for each argument an implicit conversion sequence
2219 // (13.3.3.1) that converts that argument to the corresponding
2220 // parameter of F.
2221 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002222 Candidate.Conversions[ArgIdx]
2223 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002224 SuppressUserConversions, ForceRValue,
2225 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002226 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002227 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002228 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002229 break;
2230 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002231 } else {
2232 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2233 // argument for which there is no corresponding parameter is
2234 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002235 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002236 = ImplicitConversionSequence::EllipsisConversion;
2237 }
2238 }
2239}
2240
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002241/// \brief Add all of the function declarations in the given function set to
2242/// the overload canddiate set.
2243void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2244 Expr **Args, unsigned NumArgs,
2245 OverloadCandidateSet& CandidateSet,
2246 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002247 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002248 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002249 F != FEnd; ++F) {
2250 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
Mike Stump11289f42009-09-09 15:08:12 +00002251 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002252 SuppressUserConversions);
2253 else
Douglas Gregor89026b52009-06-30 23:57:56 +00002254 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2255 /*FIXME: explicit args */false, 0, 0,
Mike Stump11289f42009-09-09 15:08:12 +00002256 Args, NumArgs, CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002257 SuppressUserConversions);
2258 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002259}
2260
Douglas Gregor436424c2008-11-18 23:14:02 +00002261/// AddMethodCandidate - Adds the given C++ member function to the set
2262/// of candidate functions, using the given function call arguments
2263/// and the object argument (@c Object). For example, in a call
2264/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2265/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2266/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002267/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2268/// a slightly hacky way to implement the overloading rules for elidable copy
2269/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002270void
Douglas Gregor436424c2008-11-18 23:14:02 +00002271Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2272 Expr **Args, unsigned NumArgs,
2273 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002274 bool SuppressUserConversions, bool ForceRValue) {
2275 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002276 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002277 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002278 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor436424c2008-11-18 23:14:02 +00002279 "Use AddConversionCandidate for conversion functions");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002280 assert(!isa<CXXConstructorDecl>(Method) &&
2281 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002282
2283 // Add this candidate
2284 CandidateSet.push_back(OverloadCandidate());
2285 OverloadCandidate& Candidate = CandidateSet.back();
2286 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002287 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002288 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002289
2290 unsigned NumArgsInProto = Proto->getNumArgs();
2291
2292 // (C++ 13.3.2p2): A candidate function having fewer than m
2293 // parameters is viable only if it has an ellipsis in its parameter
2294 // list (8.3.5).
2295 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2296 Candidate.Viable = false;
2297 return;
2298 }
2299
2300 // (C++ 13.3.2p2): A candidate function having more than m parameters
2301 // is viable only if the (m+1)st parameter has a default argument
2302 // (8.3.6). For the purposes of overload resolution, the
2303 // parameter list is truncated on the right, so that there are
2304 // exactly m parameters.
2305 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2306 if (NumArgs < MinRequiredArgs) {
2307 // Not enough arguments.
2308 Candidate.Viable = false;
2309 return;
2310 }
2311
2312 Candidate.Viable = true;
2313 Candidate.Conversions.resize(NumArgs + 1);
2314
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002315 if (Method->isStatic() || !Object)
2316 // The implicit object argument is ignored.
2317 Candidate.IgnoreObjectArgument = true;
2318 else {
2319 // Determine the implicit conversion sequence for the object
2320 // parameter.
2321 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
Mike Stump11289f42009-09-09 15:08:12 +00002322 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002323 == ImplicitConversionSequence::BadConversion) {
2324 Candidate.Viable = false;
2325 return;
2326 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002327 }
2328
2329 // Determine the implicit conversion sequences for each of the
2330 // arguments.
2331 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2332 if (ArgIdx < NumArgsInProto) {
2333 // (C++ 13.3.2p3): for F to be a viable function, there shall
2334 // exist for each argument an implicit conversion sequence
2335 // (13.3.3.1) that converts that argument to the corresponding
2336 // parameter of F.
2337 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002338 Candidate.Conversions[ArgIdx + 1]
2339 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002340 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002341 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002342 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002343 == ImplicitConversionSequence::BadConversion) {
2344 Candidate.Viable = false;
2345 break;
2346 }
2347 } else {
2348 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2349 // argument for which there is no corresponding parameter is
2350 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002351 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002352 = ImplicitConversionSequence::EllipsisConversion;
2353 }
2354 }
2355}
2356
Douglas Gregor97628d62009-08-21 00:16:32 +00002357/// \brief Add a C++ member function template as a candidate to the candidate
2358/// set, using template argument deduction to produce an appropriate member
2359/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002360void
Douglas Gregor97628d62009-08-21 00:16:32 +00002361Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2362 bool HasExplicitTemplateArgs,
2363 const TemplateArgument *ExplicitTemplateArgs,
2364 unsigned NumExplicitTemplateArgs,
2365 Expr *Object, Expr **Args, unsigned NumArgs,
2366 OverloadCandidateSet& CandidateSet,
2367 bool SuppressUserConversions,
2368 bool ForceRValue) {
2369 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002370 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002371 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002372 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002373 // candidate functions in the usual way.113) A given name can refer to one
2374 // or more function templates and also to a set of overloaded non-template
2375 // functions. In such a case, the candidate functions generated from each
2376 // function template are combined with the set of non-template candidate
2377 // functions.
2378 TemplateDeductionInfo Info(Context);
2379 FunctionDecl *Specialization = 0;
2380 if (TemplateDeductionResult Result
2381 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2382 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2383 Args, NumArgs, Specialization, Info)) {
2384 // FIXME: Record what happened with template argument deduction, so
2385 // that we can give the user a beautiful diagnostic.
2386 (void)Result;
2387 return;
2388 }
Mike Stump11289f42009-09-09 15:08:12 +00002389
Douglas Gregor97628d62009-08-21 00:16:32 +00002390 // Add the function template specialization produced by template argument
2391 // deduction as a candidate.
2392 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002393 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002394 "Specialization is not a member function?");
Mike Stump11289f42009-09-09 15:08:12 +00002395 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002396 CandidateSet, SuppressUserConversions, ForceRValue);
2397}
2398
Douglas Gregor05155d82009-08-21 23:19:43 +00002399/// \brief Add a C++ function template specialization as a candidate
2400/// in the candidate set, using template argument deduction to produce
2401/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002402void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002403Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor89026b52009-06-30 23:57:56 +00002404 bool HasExplicitTemplateArgs,
2405 const TemplateArgument *ExplicitTemplateArgs,
2406 unsigned NumExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002407 Expr **Args, unsigned NumArgs,
2408 OverloadCandidateSet& CandidateSet,
2409 bool SuppressUserConversions,
2410 bool ForceRValue) {
2411 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002412 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002413 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002414 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002415 // candidate functions in the usual way.113) A given name can refer to one
2416 // or more function templates and also to a set of overloaded non-template
2417 // functions. In such a case, the candidate functions generated from each
2418 // function template are combined with the set of non-template candidate
2419 // functions.
2420 TemplateDeductionInfo Info(Context);
2421 FunctionDecl *Specialization = 0;
2422 if (TemplateDeductionResult Result
Douglas Gregor89026b52009-06-30 23:57:56 +00002423 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2424 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2425 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002426 // FIXME: Record what happened with template argument deduction, so
2427 // that we can give the user a beautiful diagnostic.
2428 (void)Result;
2429 return;
2430 }
Mike Stump11289f42009-09-09 15:08:12 +00002431
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002432 // Add the function template specialization produced by template argument
2433 // deduction as a candidate.
2434 assert(Specialization && "Missing function template specialization?");
2435 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2436 SuppressUserConversions, ForceRValue);
2437}
Mike Stump11289f42009-09-09 15:08:12 +00002438
Douglas Gregora1f013e2008-11-07 22:36:19 +00002439/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002440/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002441/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002442/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002443/// (which may or may not be the same type as the type that the
2444/// conversion function produces).
2445void
2446Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2447 Expr *From, QualType ToType,
2448 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002449 assert(!Conversion->getDescribedFunctionTemplate() &&
2450 "Conversion function templates use AddTemplateConversionCandidate");
2451
Douglas Gregora1f013e2008-11-07 22:36:19 +00002452 // Add this candidate
2453 CandidateSet.push_back(OverloadCandidate());
2454 OverloadCandidate& Candidate = CandidateSet.back();
2455 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002456 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002457 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002458 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00002459 Candidate.FinalConversion.FromTypePtr
Douglas Gregora1f013e2008-11-07 22:36:19 +00002460 = Conversion->getConversionType().getAsOpaquePtr();
2461 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2462
Douglas Gregor436424c2008-11-18 23:14:02 +00002463 // Determine the implicit conversion sequence for the implicit
2464 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002465 Candidate.Viable = true;
2466 Candidate.Conversions.resize(1);
Douglas Gregor436424c2008-11-18 23:14:02 +00002467 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002468 // Conversion functions to a different type in the base class is visible in
2469 // the derived class. So, a derived to base conversion should not participate
2470 // in overload resolution.
2471 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2472 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump11289f42009-09-09 15:08:12 +00002473 if (Candidate.Conversions[0].ConversionKind
Douglas Gregora1f013e2008-11-07 22:36:19 +00002474 == ImplicitConversionSequence::BadConversion) {
2475 Candidate.Viable = false;
2476 return;
2477 }
2478
2479 // To determine what the conversion from the result of calling the
2480 // conversion function to the type we're eventually trying to
2481 // convert to (ToType), we need to synthesize a call to the
2482 // conversion function and attempt copy initialization from it. This
2483 // makes sure that we get the right semantics with respect to
2484 // lvalues/rvalues and the type. Fortunately, we can allocate this
2485 // call on the stack and we don't need its arguments to be
2486 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002487 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregora1f013e2008-11-07 22:36:19 +00002488 SourceLocation());
2489 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Anders Carlssona2615922009-07-31 00:48:10 +00002490 CastExpr::CK_Unknown,
Douglas Gregora11693b2008-11-12 17:17:38 +00002491 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002492
2493 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002494 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2495 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002496 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002497 Conversion->getConversionType().getNonReferenceType(),
2498 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002499 ImplicitConversionSequence ICS =
2500 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002501 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002502 /*ForceRValue=*/false,
2503 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002504
Douglas Gregora1f013e2008-11-07 22:36:19 +00002505 switch (ICS.ConversionKind) {
2506 case ImplicitConversionSequence::StandardConversion:
2507 Candidate.FinalConversion = ICS.Standard;
2508 break;
2509
2510 case ImplicitConversionSequence::BadConversion:
2511 Candidate.Viable = false;
2512 break;
2513
2514 default:
Mike Stump11289f42009-09-09 15:08:12 +00002515 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002516 "Can only end up with a standard conversion sequence or failure");
2517 }
2518}
2519
Douglas Gregor05155d82009-08-21 23:19:43 +00002520/// \brief Adds a conversion function template specialization
2521/// candidate to the overload set, using template argument deduction
2522/// to deduce the template arguments of the conversion function
2523/// template from the type that we are converting to (C++
2524/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002525void
Douglas Gregor05155d82009-08-21 23:19:43 +00002526Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2527 Expr *From, QualType ToType,
2528 OverloadCandidateSet &CandidateSet) {
2529 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2530 "Only conversion function templates permitted here");
2531
2532 TemplateDeductionInfo Info(Context);
2533 CXXConversionDecl *Specialization = 0;
2534 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002535 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002536 Specialization, Info)) {
2537 // FIXME: Record what happened with template argument deduction, so
2538 // that we can give the user a beautiful diagnostic.
2539 (void)Result;
2540 return;
2541 }
Mike Stump11289f42009-09-09 15:08:12 +00002542
Douglas Gregor05155d82009-08-21 23:19:43 +00002543 // Add the conversion function template specialization produced by
2544 // template argument deduction as a candidate.
2545 assert(Specialization && "Missing function template specialization?");
2546 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2547}
2548
Douglas Gregorab7897a2008-11-19 22:57:39 +00002549/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2550/// converts the given @c Object to a function pointer via the
2551/// conversion function @c Conversion, and then attempts to call it
2552/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2553/// the type of function that we'll eventually be calling.
2554void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002555 const FunctionProtoType *Proto,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002556 Expr *Object, Expr **Args, unsigned NumArgs,
2557 OverloadCandidateSet& CandidateSet) {
2558 CandidateSet.push_back(OverloadCandidate());
2559 OverloadCandidate& Candidate = CandidateSet.back();
2560 Candidate.Function = 0;
2561 Candidate.Surrogate = Conversion;
2562 Candidate.Viable = true;
2563 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002564 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002565 Candidate.Conversions.resize(NumArgs + 1);
2566
2567 // Determine the implicit conversion sequence for the implicit
2568 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002569 ImplicitConversionSequence ObjectInit
Douglas Gregorab7897a2008-11-19 22:57:39 +00002570 = TryObjectArgumentInitialization(Object, Conversion);
2571 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2572 Candidate.Viable = false;
2573 return;
2574 }
2575
2576 // The first conversion is actually a user-defined conversion whose
2577 // first conversion is ObjectInit's standard conversion (which is
2578 // effectively a reference binding). Record it as such.
Mike Stump11289f42009-09-09 15:08:12 +00002579 Candidate.Conversions[0].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002580 = ImplicitConversionSequence::UserDefinedConversion;
2581 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2582 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002583 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002584 = Candidate.Conversions[0].UserDefined.Before;
2585 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2586
Mike Stump11289f42009-09-09 15:08:12 +00002587 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002588 unsigned NumArgsInProto = Proto->getNumArgs();
2589
2590 // (C++ 13.3.2p2): A candidate function having fewer than m
2591 // parameters is viable only if it has an ellipsis in its parameter
2592 // list (8.3.5).
2593 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2594 Candidate.Viable = false;
2595 return;
2596 }
2597
2598 // Function types don't have any default arguments, so just check if
2599 // we have enough arguments.
2600 if (NumArgs < NumArgsInProto) {
2601 // Not enough arguments.
2602 Candidate.Viable = false;
2603 return;
2604 }
2605
2606 // Determine the implicit conversion sequences for each of the
2607 // arguments.
2608 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2609 if (ArgIdx < NumArgsInProto) {
2610 // (C++ 13.3.2p3): for F to be a viable function, there shall
2611 // exist for each argument an implicit conversion sequence
2612 // (13.3.3.1) that converts that argument to the corresponding
2613 // parameter of F.
2614 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002615 Candidate.Conversions[ArgIdx + 1]
2616 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002617 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002618 /*ForceRValue=*/false,
2619 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002620 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002621 == ImplicitConversionSequence::BadConversion) {
2622 Candidate.Viable = false;
2623 break;
2624 }
2625 } else {
2626 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2627 // argument for which there is no corresponding parameter is
2628 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002629 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002630 = ImplicitConversionSequence::EllipsisConversion;
2631 }
2632 }
2633}
2634
Mike Stump87c57ac2009-05-16 07:39:55 +00002635// FIXME: This will eventually be removed, once we've migrated all of the
2636// operator overloading logic over to the scheme used by binary operators, which
2637// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002638void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002639 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002640 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002641 OverloadCandidateSet& CandidateSet,
2642 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002643
2644 FunctionSet Functions;
2645
2646 QualType T1 = Args[0]->getType();
2647 QualType T2;
2648 if (NumArgs > 1)
2649 T2 = Args[1]->getType();
2650
2651 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002652 if (S)
2653 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002654 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2655 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2656 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2657 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2658}
2659
2660/// \brief Add overload candidates for overloaded operators that are
2661/// member functions.
2662///
2663/// Add the overloaded operator candidates that are member functions
2664/// for the operator Op that was used in an operator expression such
2665/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2666/// CandidateSet will store the added overload candidates. (C++
2667/// [over.match.oper]).
2668void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2669 SourceLocation OpLoc,
2670 Expr **Args, unsigned NumArgs,
2671 OverloadCandidateSet& CandidateSet,
2672 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002673 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2674
2675 // C++ [over.match.oper]p3:
2676 // For a unary operator @ with an operand of a type whose
2677 // cv-unqualified version is T1, and for a binary operator @ with
2678 // a left operand of a type whose cv-unqualified version is T1 and
2679 // a right operand of a type whose cv-unqualified version is T2,
2680 // three sets of candidate functions, designated member
2681 // candidates, non-member candidates and built-in candidates, are
2682 // constructed as follows:
2683 QualType T1 = Args[0]->getType();
2684 QualType T2;
2685 if (NumArgs > 1)
2686 T2 = Args[1]->getType();
2687
2688 // -- If T1 is a class type, the set of member candidates is the
2689 // result of the qualified lookup of T1::operator@
2690 // (13.3.1.1.1); otherwise, the set of member candidates is
2691 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002692 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002693 // Complete the type if it can be completed. Otherwise, we're done.
2694 if (RequireCompleteType(OpLoc, T1, PartialDiagnostic(0)))
2695 return;
Mike Stump11289f42009-09-09 15:08:12 +00002696
2697 LookupResult Operators = LookupQualifiedName(T1Rec->getDecl(), OpName,
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002698 LookupOrdinaryName, false);
Mike Stump11289f42009-09-09 15:08:12 +00002699 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002700 OperEnd = Operators.end();
2701 Oper != OperEnd;
2702 ++Oper)
Mike Stump11289f42009-09-09 15:08:12 +00002703 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
Douglas Gregor55297ac2008-12-23 00:26:44 +00002704 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor436424c2008-11-18 23:14:02 +00002705 /*SuppressUserConversions=*/false);
Douglas Gregor436424c2008-11-18 23:14:02 +00002706 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002707}
2708
Douglas Gregora11693b2008-11-12 17:17:38 +00002709/// AddBuiltinCandidate - Add a candidate for a built-in
2710/// operator. ResultTy and ParamTys are the result and parameter types
2711/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00002712/// arguments being passed to the candidate. IsAssignmentOperator
2713/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00002714/// operator. NumContextualBoolArguments is the number of arguments
2715/// (at the beginning of the argument list) that will be contextually
2716/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00002717void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00002718 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00002719 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002720 bool IsAssignmentOperator,
2721 unsigned NumContextualBoolArguments) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002722 // Add this candidate
2723 CandidateSet.push_back(OverloadCandidate());
2724 OverloadCandidate& Candidate = CandidateSet.back();
2725 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00002726 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002727 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00002728 Candidate.BuiltinTypes.ResultTy = ResultTy;
2729 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2730 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2731
2732 // Determine the implicit conversion sequences for each of the
2733 // arguments.
2734 Candidate.Viable = true;
2735 Candidate.Conversions.resize(NumArgs);
2736 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00002737 // C++ [over.match.oper]p4:
2738 // For the built-in assignment operators, conversions of the
2739 // left operand are restricted as follows:
2740 // -- no temporaries are introduced to hold the left operand, and
2741 // -- no user-defined conversions are applied to the left
2742 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00002743 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00002744 //
2745 // We block these conversions by turning off user-defined
2746 // conversions, since that is the only way that initialization of
2747 // a reference to a non-class type can occur from something that
2748 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002749 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00002750 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00002751 "Contextual conversion to bool requires bool type");
2752 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2753 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002754 Candidate.Conversions[ArgIdx]
2755 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00002756 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00002757 /*ForceRValue=*/false,
2758 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002759 }
Mike Stump11289f42009-09-09 15:08:12 +00002760 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002761 == ImplicitConversionSequence::BadConversion) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002762 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002763 break;
2764 }
Douglas Gregora11693b2008-11-12 17:17:38 +00002765 }
2766}
2767
2768/// BuiltinCandidateTypeSet - A set of types that will be used for the
2769/// candidate operator functions for built-in operators (C++
2770/// [over.built]). The types are separated into pointer types and
2771/// enumeration types.
2772class BuiltinCandidateTypeSet {
2773 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002774 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00002775
2776 /// PointerTypes - The set of pointer types that will be used in the
2777 /// built-in candidates.
2778 TypeSet PointerTypes;
2779
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002780 /// MemberPointerTypes - The set of member pointer types that will be
2781 /// used in the built-in candidates.
2782 TypeSet MemberPointerTypes;
2783
Douglas Gregora11693b2008-11-12 17:17:38 +00002784 /// EnumerationTypes - The set of enumeration types that will be
2785 /// used in the built-in candidates.
2786 TypeSet EnumerationTypes;
2787
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002788 /// Sema - The semantic analysis instance where we are building the
2789 /// candidate type set.
2790 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00002791
Douglas Gregora11693b2008-11-12 17:17:38 +00002792 /// Context - The AST context in which we will build the type sets.
2793 ASTContext &Context;
2794
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002795 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2796 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002797
2798public:
2799 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002800 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00002801
Mike Stump11289f42009-09-09 15:08:12 +00002802 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002803 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00002804
Douglas Gregor5fb53972009-01-14 15:45:31 +00002805 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2806 bool AllowExplicitConversions);
Douglas Gregora11693b2008-11-12 17:17:38 +00002807
2808 /// pointer_begin - First pointer type found;
2809 iterator pointer_begin() { return PointerTypes.begin(); }
2810
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002811 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002812 iterator pointer_end() { return PointerTypes.end(); }
2813
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002814 /// member_pointer_begin - First member pointer type found;
2815 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2816
2817 /// member_pointer_end - Past the last member pointer type found;
2818 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2819
Douglas Gregora11693b2008-11-12 17:17:38 +00002820 /// enumeration_begin - First enumeration type found;
2821 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2822
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002823 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002824 iterator enumeration_end() { return EnumerationTypes.end(); }
2825};
2826
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002827/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00002828/// the set of pointer types along with any more-qualified variants of
2829/// that type. For example, if @p Ty is "int const *", this routine
2830/// will add "int const *", "int const volatile *", "int const
2831/// restrict *", and "int const volatile restrict *" to the set of
2832/// pointer types. Returns true if the add of @p Ty itself succeeded,
2833/// false otherwise.
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002834bool
2835BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002836 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002837 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00002838 return false;
2839
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002840 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002841 QualType PointeeTy = PointerTy->getPointeeType();
2842 // FIXME: Optimize this so that we don't keep trying to add the same types.
2843
Mike Stump87c57ac2009-05-16 07:39:55 +00002844 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2845 // pointer conversions that don't cast away constness?
Douglas Gregora11693b2008-11-12 17:17:38 +00002846 if (!PointeeTy.isConstQualified())
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002847 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregora11693b2008-11-12 17:17:38 +00002848 (Context.getPointerType(PointeeTy.withConst()));
2849 if (!PointeeTy.isVolatileQualified())
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002850 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregora11693b2008-11-12 17:17:38 +00002851 (Context.getPointerType(PointeeTy.withVolatile()));
2852 if (!PointeeTy.isRestrictQualified())
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002853 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregora11693b2008-11-12 17:17:38 +00002854 (Context.getPointerType(PointeeTy.withRestrict()));
2855 }
2856
2857 return true;
2858}
2859
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002860/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2861/// to the set of pointer types along with any more-qualified variants of
2862/// that type. For example, if @p Ty is "int const *", this routine
2863/// will add "int const *", "int const volatile *", "int const
2864/// restrict *", and "int const volatile restrict *" to the set of
2865/// pointer types. Returns true if the add of @p Ty itself succeeded,
2866/// false otherwise.
2867bool
2868BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2869 QualType Ty) {
2870 // Insert this type.
2871 if (!MemberPointerTypes.insert(Ty))
2872 return false;
2873
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002874 if (const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>()) {
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002875 QualType PointeeTy = PointerTy->getPointeeType();
2876 const Type *ClassTy = PointerTy->getClass();
2877 // FIXME: Optimize this so that we don't keep trying to add the same types.
2878
2879 if (!PointeeTy.isConstQualified())
2880 AddMemberPointerWithMoreQualifiedTypeVariants
2881 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2882 if (!PointeeTy.isVolatileQualified())
2883 AddMemberPointerWithMoreQualifiedTypeVariants
2884 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2885 if (!PointeeTy.isRestrictQualified())
2886 AddMemberPointerWithMoreQualifiedTypeVariants
2887 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2888 }
2889
2890 return true;
2891}
2892
Douglas Gregora11693b2008-11-12 17:17:38 +00002893/// AddTypesConvertedFrom - Add each of the types to which the type @p
2894/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002895/// primarily interested in pointer types and enumeration types. We also
2896/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002897/// AllowUserConversions is true if we should look at the conversion
2898/// functions of a class type, and AllowExplicitConversions if we
2899/// should also include the explicit conversion functions of a class
2900/// type.
Mike Stump11289f42009-09-09 15:08:12 +00002901void
Douglas Gregor5fb53972009-01-14 15:45:31 +00002902BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2903 bool AllowUserConversions,
2904 bool AllowExplicitConversions) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002905 // Only deal with canonical types.
2906 Ty = Context.getCanonicalType(Ty);
2907
2908 // Look through reference types; they aren't part of the type of an
2909 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002910 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00002911 Ty = RefTy->getPointeeType();
2912
2913 // We don't care about qualifiers on the type.
2914 Ty = Ty.getUnqualifiedType();
2915
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002916 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002917 QualType PointeeTy = PointerTy->getPointeeType();
2918
2919 // Insert our type, and its more-qualified variants, into the set
2920 // of types.
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002921 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00002922 return;
2923
2924 // Add 'cv void*' to our set of types.
2925 if (!Ty->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002926 QualType QualVoid
Douglas Gregora11693b2008-11-12 17:17:38 +00002927 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002928 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregora11693b2008-11-12 17:17:38 +00002929 }
2930
2931 // If this is a pointer to a class type, add pointers to its bases
2932 // (with the same level of cv-qualification as the original
2933 // derived class, of course).
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002934 if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002935 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2936 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2937 Base != ClassDecl->bases_end(); ++Base) {
2938 QualType BaseTy = Context.getCanonicalType(Base->getType());
2939 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2940
2941 // Add the pointer type, recursively, so that we get all of
2942 // the indirect base classes, too.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002943 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregora11693b2008-11-12 17:17:38 +00002944 }
2945 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002946 } else if (Ty->isMemberPointerType()) {
2947 // Member pointers are far easier, since the pointee can't be converted.
2948 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2949 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00002950 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00002951 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002952 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002953 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002954 if (SemaRef.RequireCompleteType(SourceLocation(), Ty, 0)) {
2955 // No conversion functions in incomplete types.
2956 return;
2957 }
Mike Stump11289f42009-09-09 15:08:12 +00002958
Douglas Gregora11693b2008-11-12 17:17:38 +00002959 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2960 // FIXME: Visit conversion functions in the base classes, too.
Mike Stump11289f42009-09-09 15:08:12 +00002961 OverloadedFunctionDecl *Conversions
Douglas Gregora11693b2008-11-12 17:17:38 +00002962 = ClassDecl->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00002963 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregora11693b2008-11-12 17:17:38 +00002964 = Conversions->function_begin();
2965 Func != Conversions->function_end(); ++Func) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002966 CXXConversionDecl *Conv;
2967 FunctionTemplateDecl *ConvTemplate;
2968 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
2969
Mike Stump11289f42009-09-09 15:08:12 +00002970 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00002971 // about which builtin types we can convert to.
2972 if (ConvTemplate)
2973 continue;
2974
Douglas Gregor5fb53972009-01-14 15:45:31 +00002975 if (AllowExplicitConversions || !Conv->isExplicit())
2976 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregora11693b2008-11-12 17:17:38 +00002977 }
2978 }
2979 }
2980}
2981
Douglas Gregor84605ae2009-08-24 13:43:27 +00002982/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
2983/// the volatile- and non-volatile-qualified assignment operators for the
2984/// given type to the candidate set.
2985static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
2986 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00002987 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00002988 unsigned NumArgs,
2989 OverloadCandidateSet &CandidateSet) {
2990 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002991
Douglas Gregor84605ae2009-08-24 13:43:27 +00002992 // T& operator=(T&, T)
2993 ParamTypes[0] = S.Context.getLValueReferenceType(T);
2994 ParamTypes[1] = T;
2995 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2996 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002997
Douglas Gregor84605ae2009-08-24 13:43:27 +00002998 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
2999 // volatile T& operator=(volatile T&, T)
3000 ParamTypes[0] = S.Context.getLValueReferenceType(T.withVolatile());
3001 ParamTypes[1] = T;
3002 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003003 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003004 }
3005}
Mike Stump11289f42009-09-09 15:08:12 +00003006
Douglas Gregord08452f2008-11-19 15:42:04 +00003007/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3008/// operator overloads to the candidate set (C++ [over.built]), based
3009/// on the operator @p Op and the arguments given. For example, if the
3010/// operator is a binary '+', this routine might add "int
3011/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003012void
Mike Stump11289f42009-09-09 15:08:12 +00003013Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregord08452f2008-11-19 15:42:04 +00003014 Expr **Args, unsigned NumArgs,
3015 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003016 // The set of "promoted arithmetic types", which are the arithmetic
3017 // types are that preserved by promotion (C++ [over.built]p2). Note
3018 // that the first few of these types are the promoted integral
3019 // types; these types need to be first.
3020 // FIXME: What about complex?
3021 const unsigned FirstIntegralType = 0;
3022 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003023 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003024 LastPromotedIntegralType = 13;
3025 const unsigned FirstPromotedArithmeticType = 7,
3026 LastPromotedArithmeticType = 16;
3027 const unsigned NumArithmeticTypes = 16;
3028 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003029 Context.BoolTy, Context.CharTy, Context.WCharTy,
3030// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003031 Context.SignedCharTy, Context.ShortTy,
3032 Context.UnsignedCharTy, Context.UnsignedShortTy,
3033 Context.IntTy, Context.LongTy, Context.LongLongTy,
3034 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3035 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3036 };
3037
3038 // Find all of the types that the arguments can convert to, but only
3039 // if the operator we're looking at has built-in operator candidates
3040 // that make use of these types.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003041 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003042 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3043 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003044 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003045 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003046 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003047 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003048 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003049 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3050 true,
3051 (Op == OO_Exclaim ||
3052 Op == OO_AmpAmp ||
3053 Op == OO_PipePipe));
Douglas Gregora11693b2008-11-12 17:17:38 +00003054 }
3055
3056 bool isComparison = false;
3057 switch (Op) {
3058 case OO_None:
3059 case NUM_OVERLOADED_OPERATORS:
3060 assert(false && "Expected an overloaded operator");
3061 break;
3062
Douglas Gregord08452f2008-11-19 15:42:04 +00003063 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003064 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003065 goto UnaryStar;
3066 else
3067 goto BinaryStar;
3068 break;
3069
3070 case OO_Plus: // '+' is either unary or binary
3071 if (NumArgs == 1)
3072 goto UnaryPlus;
3073 else
3074 goto BinaryPlus;
3075 break;
3076
3077 case OO_Minus: // '-' is either unary or binary
3078 if (NumArgs == 1)
3079 goto UnaryMinus;
3080 else
3081 goto BinaryMinus;
3082 break;
3083
3084 case OO_Amp: // '&' is either unary or binary
3085 if (NumArgs == 1)
3086 goto UnaryAmp;
3087 else
3088 goto BinaryAmp;
3089
3090 case OO_PlusPlus:
3091 case OO_MinusMinus:
3092 // C++ [over.built]p3:
3093 //
3094 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3095 // is either volatile or empty, there exist candidate operator
3096 // functions of the form
3097 //
3098 // VQ T& operator++(VQ T&);
3099 // T operator++(VQ T&, int);
3100 //
3101 // C++ [over.built]p4:
3102 //
3103 // For every pair (T, VQ), where T is an arithmetic type other
3104 // than bool, and VQ is either volatile or empty, there exist
3105 // candidate operator functions of the form
3106 //
3107 // VQ T& operator--(VQ T&);
3108 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003109 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003110 Arith < NumArithmeticTypes; ++Arith) {
3111 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003112 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003113 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003114
3115 // Non-volatile version.
3116 if (NumArgs == 1)
3117 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3118 else
3119 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3120
3121 // Volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003122 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregord08452f2008-11-19 15:42:04 +00003123 if (NumArgs == 1)
3124 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3125 else
3126 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3127 }
3128
3129 // C++ [over.built]p5:
3130 //
3131 // For every pair (T, VQ), where T is a cv-qualified or
3132 // cv-unqualified object type, and VQ is either volatile or
3133 // empty, there exist candidate operator functions of the form
3134 //
3135 // T*VQ& operator++(T*VQ&);
3136 // T*VQ& operator--(T*VQ&);
3137 // T* operator++(T*VQ&, int);
3138 // T* operator--(T*VQ&, int);
3139 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3140 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3141 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003142 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003143 continue;
3144
Mike Stump11289f42009-09-09 15:08:12 +00003145 QualType ParamTypes[2] = {
3146 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003147 };
Mike Stump11289f42009-09-09 15:08:12 +00003148
Douglas Gregord08452f2008-11-19 15:42:04 +00003149 // Without volatile
3150 if (NumArgs == 1)
3151 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3152 else
3153 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3154
3155 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3156 // With volatile
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003157 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregord08452f2008-11-19 15:42:04 +00003158 if (NumArgs == 1)
3159 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3160 else
3161 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3162 }
3163 }
3164 break;
3165
3166 UnaryStar:
3167 // C++ [over.built]p6:
3168 // For every cv-qualified or cv-unqualified object type T, there
3169 // exist candidate operator functions of the form
3170 //
3171 // T& operator*(T*);
3172 //
3173 // C++ [over.built]p7:
3174 // For every function type T, there exist candidate operator
3175 // functions of the form
3176 // T& operator*(T*);
3177 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3178 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3179 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003180 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003181 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003182 &ParamTy, Args, 1, CandidateSet);
3183 }
3184 break;
3185
3186 UnaryPlus:
3187 // C++ [over.built]p8:
3188 // For every type T, there exist candidate operator functions of
3189 // the form
3190 //
3191 // T* operator+(T*);
3192 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3193 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3194 QualType ParamTy = *Ptr;
3195 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3196 }
Mike Stump11289f42009-09-09 15:08:12 +00003197
Douglas Gregord08452f2008-11-19 15:42:04 +00003198 // Fall through
3199
3200 UnaryMinus:
3201 // C++ [over.built]p9:
3202 // For every promoted arithmetic type T, there exist candidate
3203 // operator functions of the form
3204 //
3205 // T operator+(T);
3206 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003207 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003208 Arith < LastPromotedArithmeticType; ++Arith) {
3209 QualType ArithTy = ArithmeticTypes[Arith];
3210 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3211 }
3212 break;
3213
3214 case OO_Tilde:
3215 // C++ [over.built]p10:
3216 // For every promoted integral type T, there exist candidate
3217 // operator functions of the form
3218 //
3219 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003220 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003221 Int < LastPromotedIntegralType; ++Int) {
3222 QualType IntTy = ArithmeticTypes[Int];
3223 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3224 }
3225 break;
3226
Douglas Gregora11693b2008-11-12 17:17:38 +00003227 case OO_New:
3228 case OO_Delete:
3229 case OO_Array_New:
3230 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003231 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003232 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003233 break;
3234
3235 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003236 UnaryAmp:
3237 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003238 // C++ [over.match.oper]p3:
3239 // -- For the operator ',', the unary operator '&', or the
3240 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003241 break;
3242
Douglas Gregor84605ae2009-08-24 13:43:27 +00003243 case OO_EqualEqual:
3244 case OO_ExclaimEqual:
3245 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003246 // For every pointer to member type T, there exist candidate operator
3247 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003248 //
3249 // bool operator==(T,T);
3250 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003251 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003252 MemPtr = CandidateTypes.member_pointer_begin(),
3253 MemPtrEnd = CandidateTypes.member_pointer_end();
3254 MemPtr != MemPtrEnd;
3255 ++MemPtr) {
3256 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3257 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3258 }
Mike Stump11289f42009-09-09 15:08:12 +00003259
Douglas Gregor84605ae2009-08-24 13:43:27 +00003260 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003261
Douglas Gregora11693b2008-11-12 17:17:38 +00003262 case OO_Less:
3263 case OO_Greater:
3264 case OO_LessEqual:
3265 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003266 // C++ [over.built]p15:
3267 //
3268 // For every pointer or enumeration type T, there exist
3269 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003270 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003271 // bool operator<(T, T);
3272 // bool operator>(T, T);
3273 // bool operator<=(T, T);
3274 // bool operator>=(T, T);
3275 // bool operator==(T, T);
3276 // bool operator!=(T, T);
3277 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3278 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3279 QualType ParamTypes[2] = { *Ptr, *Ptr };
3280 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3281 }
Mike Stump11289f42009-09-09 15:08:12 +00003282 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003283 = CandidateTypes.enumeration_begin();
3284 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3285 QualType ParamTypes[2] = { *Enum, *Enum };
3286 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3287 }
3288
3289 // Fall through.
3290 isComparison = true;
3291
Douglas Gregord08452f2008-11-19 15:42:04 +00003292 BinaryPlus:
3293 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003294 if (!isComparison) {
3295 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3296
3297 // C++ [over.built]p13:
3298 //
3299 // For every cv-qualified or cv-unqualified object type T
3300 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003301 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003302 // T* operator+(T*, ptrdiff_t);
3303 // T& operator[](T*, ptrdiff_t); [BELOW]
3304 // T* operator-(T*, ptrdiff_t);
3305 // T* operator+(ptrdiff_t, T*);
3306 // T& operator[](ptrdiff_t, T*); [BELOW]
3307 //
3308 // C++ [over.built]p14:
3309 //
3310 // For every T, where T is a pointer to object type, there
3311 // exist candidate operator functions of the form
3312 //
3313 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003314 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003315 = CandidateTypes.pointer_begin();
3316 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3317 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3318
3319 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3320 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3321
3322 if (Op == OO_Plus) {
3323 // T* operator+(ptrdiff_t, T*);
3324 ParamTypes[0] = ParamTypes[1];
3325 ParamTypes[1] = *Ptr;
3326 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3327 } else {
3328 // ptrdiff_t operator-(T, T);
3329 ParamTypes[1] = *Ptr;
3330 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3331 Args, 2, CandidateSet);
3332 }
3333 }
3334 }
3335 // Fall through
3336
Douglas Gregora11693b2008-11-12 17:17:38 +00003337 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003338 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003339 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003340 // C++ [over.built]p12:
3341 //
3342 // For every pair of promoted arithmetic types L and R, there
3343 // exist candidate operator functions of the form
3344 //
3345 // LR operator*(L, R);
3346 // LR operator/(L, R);
3347 // LR operator+(L, R);
3348 // LR operator-(L, R);
3349 // bool operator<(L, R);
3350 // bool operator>(L, R);
3351 // bool operator<=(L, R);
3352 // bool operator>=(L, R);
3353 // bool operator==(L, R);
3354 // bool operator!=(L, R);
3355 //
3356 // where LR is the result of the usual arithmetic conversions
3357 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003358 //
3359 // C++ [over.built]p24:
3360 //
3361 // For every pair of promoted arithmetic types L and R, there exist
3362 // candidate operator functions of the form
3363 //
3364 // LR operator?(bool, L, R);
3365 //
3366 // where LR is the result of the usual arithmetic conversions
3367 // between types L and R.
3368 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003369 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003370 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003371 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003372 Right < LastPromotedArithmeticType; ++Right) {
3373 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003374 QualType Result
3375 = isComparison
3376 ? Context.BoolTy
3377 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003378 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3379 }
3380 }
3381 break;
3382
3383 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003384 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003385 case OO_Caret:
3386 case OO_Pipe:
3387 case OO_LessLess:
3388 case OO_GreaterGreater:
3389 // C++ [over.built]p17:
3390 //
3391 // For every pair of promoted integral types L and R, there
3392 // exist candidate operator functions of the form
3393 //
3394 // LR operator%(L, R);
3395 // LR operator&(L, R);
3396 // LR operator^(L, R);
3397 // LR operator|(L, R);
3398 // L operator<<(L, R);
3399 // L operator>>(L, R);
3400 //
3401 // where LR is the result of the usual arithmetic conversions
3402 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003403 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003404 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003405 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003406 Right < LastPromotedIntegralType; ++Right) {
3407 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3408 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3409 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003410 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003411 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3412 }
3413 }
3414 break;
3415
3416 case OO_Equal:
3417 // C++ [over.built]p20:
3418 //
3419 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003420 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003421 // empty, there exist candidate operator functions of the form
3422 //
3423 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003424 for (BuiltinCandidateTypeSet::iterator
3425 Enum = CandidateTypes.enumeration_begin(),
3426 EnumEnd = CandidateTypes.enumeration_end();
3427 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003428 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003429 CandidateSet);
3430 for (BuiltinCandidateTypeSet::iterator
3431 MemPtr = CandidateTypes.member_pointer_begin(),
3432 MemPtrEnd = CandidateTypes.member_pointer_end();
3433 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003434 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003435 CandidateSet);
3436 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003437
3438 case OO_PlusEqual:
3439 case OO_MinusEqual:
3440 // C++ [over.built]p19:
3441 //
3442 // For every pair (T, VQ), where T is any type and VQ is either
3443 // volatile or empty, there exist candidate operator functions
3444 // of the form
3445 //
3446 // T*VQ& operator=(T*VQ&, T*);
3447 //
3448 // C++ [over.built]p21:
3449 //
3450 // For every pair (T, VQ), where T is a cv-qualified or
3451 // cv-unqualified object type and VQ is either volatile or
3452 // empty, there exist candidate operator functions of the form
3453 //
3454 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3455 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3456 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3457 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3458 QualType ParamTypes[2];
3459 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3460
3461 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003462 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003463 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3464 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003465
Douglas Gregord08452f2008-11-19 15:42:04 +00003466 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3467 // volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003468 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregorc5e61072009-01-13 00:52:54 +00003469 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3470 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003471 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003472 }
3473 // Fall through.
3474
3475 case OO_StarEqual:
3476 case OO_SlashEqual:
3477 // C++ [over.built]p18:
3478 //
3479 // For every triple (L, VQ, R), where L is an arithmetic type,
3480 // VQ is either volatile or empty, and R is a promoted
3481 // arithmetic type, there exist candidate operator functions of
3482 // the form
3483 //
3484 // VQ L& operator=(VQ L&, R);
3485 // VQ L& operator*=(VQ L&, R);
3486 // VQ L& operator/=(VQ L&, R);
3487 // VQ L& operator+=(VQ L&, R);
3488 // VQ L& operator-=(VQ L&, R);
3489 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003490 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003491 Right < LastPromotedArithmeticType; ++Right) {
3492 QualType ParamTypes[2];
3493 ParamTypes[1] = ArithmeticTypes[Right];
3494
3495 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003496 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003497 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3498 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003499
3500 // Add this built-in operator as a candidate (VQ is 'volatile').
3501 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003502 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003503 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3504 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003505 }
3506 }
3507 break;
3508
3509 case OO_PercentEqual:
3510 case OO_LessLessEqual:
3511 case OO_GreaterGreaterEqual:
3512 case OO_AmpEqual:
3513 case OO_CaretEqual:
3514 case OO_PipeEqual:
3515 // C++ [over.built]p22:
3516 //
3517 // For every triple (L, VQ, R), where L is an integral type, VQ
3518 // is either volatile or empty, and R is a promoted integral
3519 // type, there exist candidate operator functions of the form
3520 //
3521 // VQ L& operator%=(VQ L&, R);
3522 // VQ L& operator<<=(VQ L&, R);
3523 // VQ L& operator>>=(VQ L&, R);
3524 // VQ L& operator&=(VQ L&, R);
3525 // VQ L& operator^=(VQ L&, R);
3526 // VQ L& operator|=(VQ L&, R);
3527 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003528 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003529 Right < LastPromotedIntegralType; ++Right) {
3530 QualType ParamTypes[2];
3531 ParamTypes[1] = ArithmeticTypes[Right];
3532
3533 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003534 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003535 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3536
3537 // Add this built-in operator as a candidate (VQ is 'volatile').
3538 ParamTypes[0] = ArithmeticTypes[Left];
3539 ParamTypes[0].addVolatile();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003540 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003541 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3542 }
3543 }
3544 break;
3545
Douglas Gregord08452f2008-11-19 15:42:04 +00003546 case OO_Exclaim: {
3547 // C++ [over.operator]p23:
3548 //
3549 // There also exist candidate operator functions of the form
3550 //
Mike Stump11289f42009-09-09 15:08:12 +00003551 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003552 // bool operator&&(bool, bool); [BELOW]
3553 // bool operator||(bool, bool); [BELOW]
3554 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003555 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3556 /*IsAssignmentOperator=*/false,
3557 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003558 break;
3559 }
3560
Douglas Gregora11693b2008-11-12 17:17:38 +00003561 case OO_AmpAmp:
3562 case OO_PipePipe: {
3563 // C++ [over.operator]p23:
3564 //
3565 // There also exist candidate operator functions of the form
3566 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003567 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003568 // bool operator&&(bool, bool);
3569 // bool operator||(bool, bool);
3570 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003571 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3572 /*IsAssignmentOperator=*/false,
3573 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003574 break;
3575 }
3576
3577 case OO_Subscript:
3578 // C++ [over.built]p13:
3579 //
3580 // For every cv-qualified or cv-unqualified object type T there
3581 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003582 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003583 // T* operator+(T*, ptrdiff_t); [ABOVE]
3584 // T& operator[](T*, ptrdiff_t);
3585 // T* operator-(T*, ptrdiff_t); [ABOVE]
3586 // T* operator+(ptrdiff_t, T*); [ABOVE]
3587 // T& operator[](ptrdiff_t, T*);
3588 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3589 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3590 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003591 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003592 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003593
3594 // T& operator[](T*, ptrdiff_t)
3595 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3596
3597 // T& operator[](ptrdiff_t, T*);
3598 ParamTypes[0] = ParamTypes[1];
3599 ParamTypes[1] = *Ptr;
3600 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3601 }
3602 break;
3603
3604 case OO_ArrowStar:
3605 // FIXME: No support for pointer-to-members yet.
3606 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003607
3608 case OO_Conditional:
3609 // Note that we don't consider the first argument, since it has been
3610 // contextually converted to bool long ago. The candidates below are
3611 // therefore added as binary.
3612 //
3613 // C++ [over.built]p24:
3614 // For every type T, where T is a pointer or pointer-to-member type,
3615 // there exist candidate operator functions of the form
3616 //
3617 // T operator?(bool, T, T);
3618 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00003619 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3620 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3621 QualType ParamTypes[2] = { *Ptr, *Ptr };
3622 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3623 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003624 for (BuiltinCandidateTypeSet::iterator Ptr =
3625 CandidateTypes.member_pointer_begin(),
3626 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3627 QualType ParamTypes[2] = { *Ptr, *Ptr };
3628 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3629 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003630 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00003631 }
3632}
3633
Douglas Gregore254f902009-02-04 00:32:51 +00003634/// \brief Add function candidates found via argument-dependent lookup
3635/// to the set of overloading candidates.
3636///
3637/// This routine performs argument-dependent name lookup based on the
3638/// given function name (which may also be an operator name) and adds
3639/// all of the overload candidates found by ADL to the overload
3640/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00003641void
Douglas Gregore254f902009-02-04 00:32:51 +00003642Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3643 Expr **Args, unsigned NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00003644 bool HasExplicitTemplateArgs,
3645 const TemplateArgument *ExplicitTemplateArgs,
3646 unsigned NumExplicitTemplateArgs,
3647 OverloadCandidateSet& CandidateSet,
3648 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003649 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00003650
Douglas Gregorcabea402009-09-22 15:41:20 +00003651 // FIXME: Should we be trafficking in canonical function decls throughout?
3652
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003653 // Record all of the function candidates that we've already
3654 // added to the overload set, so that we don't add those same
3655 // candidates a second time.
3656 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3657 CandEnd = CandidateSet.end();
3658 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003659 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003660 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003661 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3662 Functions.insert(FunTmpl);
3663 }
Douglas Gregore254f902009-02-04 00:32:51 +00003664
Douglas Gregorcabea402009-09-22 15:41:20 +00003665 // FIXME: Pass in the explicit template arguments?
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003666 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00003667
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003668 // Erase all of the candidates we already knew about.
3669 // FIXME: This is suboptimal. Is there a better way?
3670 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3671 CandEnd = CandidateSet.end();
3672 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003673 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003674 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003675 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3676 Functions.erase(FunTmpl);
3677 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003678
3679 // For each of the ADL candidates we found, add it to the overload
3680 // set.
3681 for (FunctionSet::iterator Func = Functions.begin(),
3682 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00003683 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003684 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
3685 if (HasExplicitTemplateArgs)
3686 continue;
3687
3688 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
3689 false, false, PartialOverloading);
3690 } else
Mike Stump11289f42009-09-09 15:08:12 +00003691 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00003692 HasExplicitTemplateArgs,
3693 ExplicitTemplateArgs,
3694 NumExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003695 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00003696 }
Douglas Gregore254f902009-02-04 00:32:51 +00003697}
3698
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003699/// isBetterOverloadCandidate - Determines whether the first overload
3700/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00003701bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003702Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00003703 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003704 // Define viable functions to be better candidates than non-viable
3705 // functions.
3706 if (!Cand2.Viable)
3707 return Cand1.Viable;
3708 else if (!Cand1.Viable)
3709 return false;
3710
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003711 // C++ [over.match.best]p1:
3712 //
3713 // -- if F is a static member function, ICS1(F) is defined such
3714 // that ICS1(F) is neither better nor worse than ICS1(G) for
3715 // any function G, and, symmetrically, ICS1(G) is neither
3716 // better nor worse than ICS1(F).
3717 unsigned StartArg = 0;
3718 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3719 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003720
Douglas Gregord3cb3562009-07-07 23:38:56 +00003721 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00003722 // A viable function F1 is defined to be a better function than another
3723 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00003724 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003725 unsigned NumArgs = Cand1.Conversions.size();
3726 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3727 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003728 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003729 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3730 Cand2.Conversions[ArgIdx])) {
3731 case ImplicitConversionSequence::Better:
3732 // Cand1 has a better conversion sequence.
3733 HasBetterConversion = true;
3734 break;
3735
3736 case ImplicitConversionSequence::Worse:
3737 // Cand1 can't be better than Cand2.
3738 return false;
3739
3740 case ImplicitConversionSequence::Indistinguishable:
3741 // Do nothing.
3742 break;
3743 }
3744 }
3745
Mike Stump11289f42009-09-09 15:08:12 +00003746 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00003747 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003748 if (HasBetterConversion)
3749 return true;
3750
Mike Stump11289f42009-09-09 15:08:12 +00003751 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00003752 // specialization, or, if not that,
3753 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3754 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3755 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003756
3757 // -- F1 and F2 are function template specializations, and the function
3758 // template for F1 is more specialized than the template for F2
3759 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00003760 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00003761 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3762 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00003763 if (FunctionTemplateDecl *BetterTemplate
3764 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3765 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00003766 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
3767 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00003768 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003769
Douglas Gregora1f013e2008-11-07 22:36:19 +00003770 // -- the context is an initialization by user-defined conversion
3771 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3772 // from the return type of F1 to the destination type (i.e.,
3773 // the type of the entity being initialized) is a better
3774 // conversion sequence than the standard conversion sequence
3775 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00003776 if (Cand1.Function && Cand2.Function &&
3777 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003778 isa<CXXConversionDecl>(Cand2.Function)) {
3779 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3780 Cand2.FinalConversion)) {
3781 case ImplicitConversionSequence::Better:
3782 // Cand1 has a better conversion sequence.
3783 return true;
3784
3785 case ImplicitConversionSequence::Worse:
3786 // Cand1 can't be better than Cand2.
3787 return false;
3788
3789 case ImplicitConversionSequence::Indistinguishable:
3790 // Do nothing
3791 break;
3792 }
3793 }
3794
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003795 return false;
3796}
3797
Mike Stump11289f42009-09-09 15:08:12 +00003798/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003799/// within an overload candidate set.
3800///
3801/// \param CandidateSet the set of candidate functions.
3802///
3803/// \param Loc the location of the function name (or operator symbol) for
3804/// which overload resolution occurs.
3805///
Mike Stump11289f42009-09-09 15:08:12 +00003806/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003807/// function, Best points to the candidate function found.
3808///
3809/// \returns The result of overload resolution.
Mike Stump11289f42009-09-09 15:08:12 +00003810Sema::OverloadingResult
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003811Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003812 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00003813 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003814 // Find the best viable function.
3815 Best = CandidateSet.end();
3816 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3817 Cand != CandidateSet.end(); ++Cand) {
3818 if (Cand->Viable) {
3819 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3820 Best = Cand;
3821 }
3822 }
3823
3824 // If we didn't find any viable functions, abort.
3825 if (Best == CandidateSet.end())
3826 return OR_No_Viable_Function;
3827
3828 // Make sure that this function is better than every other viable
3829 // function. If not, we have an ambiguity.
3830 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3831 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00003832 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003833 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00003834 !isBetterOverloadCandidate(*Best, *Cand)) {
3835 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003836 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003837 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003838 }
Mike Stump11289f42009-09-09 15:08:12 +00003839
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003840 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00003841 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00003842 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003843 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00003844 return OR_Deleted;
3845
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003846 // C++ [basic.def.odr]p2:
3847 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00003848 // when referred to from a potentially-evaluated expression. [Note: this
3849 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003850 // (clause 13), user-defined conversions (12.3.2), allocation function for
3851 // placement new (5.3.4), as well as non-default initialization (8.5).
3852 if (Best->Function)
3853 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003854 return OR_Success;
3855}
3856
3857/// PrintOverloadCandidates - When overload resolution fails, prints
3858/// diagnostic messages containing the candidates in the candidate
3859/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump11289f42009-09-09 15:08:12 +00003860void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003861Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003862 bool OnlyViable) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003863 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3864 LastCand = CandidateSet.end();
3865 for (; Cand != LastCand; ++Cand) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003866 if (Cand->Viable || !OnlyViable) {
3867 if (Cand->Function) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003868 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003869 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003870 // Deleted or "unavailable" function.
3871 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3872 << Cand->Function->isDeleted();
Douglas Gregor4fb9cde8e2009-09-15 20:11:42 +00003873 } else if (FunctionTemplateDecl *FunTmpl
3874 = Cand->Function->getPrimaryTemplate()) {
3875 // Function template specialization
3876 // FIXME: Give a better reason!
3877 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
3878 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
3879 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor171c45a2009-02-18 21:56:37 +00003880 } else {
3881 // Normal function
Fariborz Jahanian21ccf062009-09-23 00:58:07 +00003882 bool errReported = false;
3883 if (!Cand->Viable && Cand->Conversions.size() > 0) {
3884 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
3885 const ImplicitConversionSequence &Conversion =
3886 Cand->Conversions[i];
3887 if ((Conversion.ConversionKind !=
3888 ImplicitConversionSequence::BadConversion) ||
3889 Conversion.ConversionFunctionSet.size() == 0)
3890 continue;
3891 Diag(Cand->Function->getLocation(),
3892 diag::err_ovl_candidate_not_viable) << (i+1);
3893 errReported = true;
3894 for (int j = Conversion.ConversionFunctionSet.size()-1;
3895 j >= 0; j--) {
3896 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
3897 Diag(Func->getLocation(), diag::err_ovl_candidate);
3898 }
3899 }
3900 }
3901 if (!errReported)
3902 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor171c45a2009-02-18 21:56:37 +00003903 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00003904 } else if (Cand->IsSurrogate) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003905 // Desugar the type of the surrogate down to a function type,
3906 // retaining as many typedefs as possible while still showing
3907 // the function type (and, therefore, its parameter types).
3908 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003909 bool isLValueReference = false;
3910 bool isRValueReference = false;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003911 bool isPointer = false;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003912 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003913 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003914 FnType = FnTypeRef->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003915 isLValueReference = true;
3916 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003917 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003918 FnType = FnTypeRef->getPointeeType();
3919 isRValueReference = true;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003920 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003921 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003922 FnType = FnTypePtr->getPointeeType();
3923 isPointer = true;
3924 }
3925 // Desugar down to a function type.
John McCall9dd450b2009-09-21 23:43:11 +00003926 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003927 // Reconstruct the pointer/reference as appropriate.
3928 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003929 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3930 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00003931
Douglas Gregorab7897a2008-11-19 22:57:39 +00003932 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003933 << FnType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003934 } else {
3935 // FIXME: We need to get the identifier in here
Mike Stump87c57ac2009-05-16 07:39:55 +00003936 // FIXME: Do we want the error message to point at the operator?
3937 // (built-ins won't have a location)
Mike Stump11289f42009-09-09 15:08:12 +00003938 QualType FnType
Douglas Gregora11693b2008-11-12 17:17:38 +00003939 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3940 Cand->BuiltinTypes.ParamTypes,
3941 Cand->Conversions.size(),
3942 false, 0);
3943
Chris Lattner1e5665e2008-11-24 06:25:27 +00003944 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003945 }
3946 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003947 }
3948}
3949
Douglas Gregorcd695e52008-11-10 20:40:00 +00003950/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3951/// an overloaded function (C++ [over.over]), where @p From is an
3952/// expression with overloaded function type and @p ToType is the type
3953/// we're trying to resolve to. For example:
3954///
3955/// @code
3956/// int f(double);
3957/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00003958///
Douglas Gregorcd695e52008-11-10 20:40:00 +00003959/// int (*pfd)(double) = f; // selects f(double)
3960/// @endcode
3961///
3962/// This routine returns the resulting FunctionDecl if it could be
3963/// resolved, and NULL otherwise. When @p Complain is true, this
3964/// routine will emit diagnostics if there is an error.
3965FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003966Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00003967 bool Complain) {
3968 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003969 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003970 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00003971 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003972 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00003973 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003974 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003975 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00003976 FunctionType = MemTypePtr->getPointeeType();
3977 IsMember = true;
3978 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00003979
3980 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00003981 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00003982 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00003983 return 0;
3984
3985 // Find the actual overloaded function declaration.
3986 OverloadedFunctionDecl *Ovl = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003987
Douglas Gregorcd695e52008-11-10 20:40:00 +00003988 // C++ [over.over]p1:
3989 // [...] [Note: any redundant set of parentheses surrounding the
3990 // overloaded function name is ignored (5.1). ]
3991 Expr *OvlExpr = From->IgnoreParens();
3992
3993 // C++ [over.over]p1:
3994 // [...] The overloaded function name can be preceded by the &
3995 // operator.
3996 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3997 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3998 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3999 }
4000
4001 // Try to dig out the overloaded function.
Douglas Gregor9b146582009-07-08 20:55:45 +00004002 FunctionTemplateDecl *FunctionTemplate = 0;
4003 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004004 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor9b146582009-07-08 20:55:45 +00004005 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
4006 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004007
Mike Stump11289f42009-09-09 15:08:12 +00004008 // If there's no overloaded function declaration or function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00004009 // we're done.
4010 if (!Ovl && !FunctionTemplate)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004011 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004012
Douglas Gregor9b146582009-07-08 20:55:45 +00004013 OverloadIterator Fun;
4014 if (Ovl)
4015 Fun = Ovl;
4016 else
4017 Fun = FunctionTemplate;
Mike Stump11289f42009-09-09 15:08:12 +00004018
Douglas Gregorcd695e52008-11-10 20:40:00 +00004019 // Look through all of the overloaded functions, searching for one
4020 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004021 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Mike Stump11289f42009-09-09 15:08:12 +00004022
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004023 bool FoundNonTemplateFunction = false;
Douglas Gregor9b146582009-07-08 20:55:45 +00004024 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004025 // C++ [over.over]p3:
4026 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00004027 // targets of type "pointer-to-function" or "reference-to-function."
4028 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004029 // type "pointer-to-member-function."
4030 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004031
Mike Stump11289f42009-09-09 15:08:12 +00004032 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregor9b146582009-07-08 20:55:45 +00004033 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Mike Stump11289f42009-09-09 15:08:12 +00004034 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004035 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004036 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004037 // static when converting to member pointer.
4038 if (Method->isStatic() == IsMember)
4039 continue;
4040 } else if (IsMember)
4041 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004042
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004043 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004044 // If the name is a function template, template argument deduction is
4045 // done (14.8.2.2), and if the argument deduction succeeds, the
4046 // resulting template argument list is used to generate a single
4047 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004048 // overloaded functions considered.
Douglas Gregor9b146582009-07-08 20:55:45 +00004049 FunctionDecl *Specialization = 0;
4050 TemplateDeductionInfo Info(Context);
4051 if (TemplateDeductionResult Result
4052 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
4053 /*FIXME:*/0, /*FIXME:*/0,
4054 FunctionType, Specialization, Info)) {
4055 // FIXME: make a note of the failed deduction for diagnostics.
4056 (void)Result;
4057 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004058 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004059 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004060 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004061 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004062 }
4063 }
Mike Stump11289f42009-09-09 15:08:12 +00004064
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004065 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
4066 // Skip non-static functions when converting to pointer, and static
4067 // when converting to member pointer.
4068 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004069 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004070 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004071 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004072
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004073 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004074 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004075 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004076 FoundNonTemplateFunction = true;
4077 }
Mike Stump11289f42009-09-09 15:08:12 +00004078 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004079 }
4080
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004081 // If there were 0 or 1 matches, we're done.
4082 if (Matches.empty())
4083 return 0;
4084 else if (Matches.size() == 1)
4085 return *Matches.begin();
4086
4087 // C++ [over.over]p4:
4088 // If more than one function is selected, [...]
4089 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
Douglas Gregor05155d82009-08-21 23:19:43 +00004090 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004091 if (FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004092 // [...] any function template specializations in the set are
4093 // eliminated if the set also contains a non-template function, [...]
4094 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004095 if ((*M)->getPrimaryTemplate() == 0)
4096 RemainingMatches.push_back(*M);
4097 } else {
Douglas Gregor05155d82009-08-21 23:19:43 +00004098 // [...] and any given function template specialization F1 is
4099 // eliminated if the set contains a second function template
4100 // specialization whose function template is more specialized
4101 // than the function template of F1 according to the partial
4102 // ordering rules of 14.5.5.2.
4103
4104 // The algorithm specified above is quadratic. We instead use a
4105 // two-pass algorithm (similar to the one used to identify the
4106 // best viable function in an overload set) that identifies the
4107 // best function template (if it exists).
4108 MatchIter Best = Matches.begin();
4109 MatchIter M = Best, MEnd = Matches.end();
4110 // Find the most specialized function.
4111 for (++M; M != MEnd; ++M)
4112 if (getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4113 (*Best)->getPrimaryTemplate(),
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004114 TPOC_Other)
Douglas Gregor05155d82009-08-21 23:19:43 +00004115 == (*M)->getPrimaryTemplate())
4116 Best = M;
4117
4118 // Determine whether this function template is more specialized
4119 // that all of the others.
4120 bool Ambiguous = false;
4121 for (M = Matches.begin(); M != MEnd; ++M) {
4122 if (M != Best &&
4123 getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4124 (*Best)->getPrimaryTemplate(),
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004125 TPOC_Other)
Douglas Gregor05155d82009-08-21 23:19:43 +00004126 != (*Best)->getPrimaryTemplate()) {
4127 Ambiguous = true;
4128 break;
4129 }
4130 }
4131
4132 // If one function template was more specialized than all of the
4133 // others, return it.
4134 if (!Ambiguous)
4135 return *Best;
4136
4137 // We could not find a most-specialized function template, which
4138 // is equivalent to having a set of function templates with more
4139 // than one such template. So, we place all of the function
4140 // templates into the set of remaining matches and produce a
4141 // diagnostic below. FIXME: we could perform the quadratic
4142 // algorithm here, pruning the result set to limit the number of
4143 // candidates output later.
Douglas Gregor48bc3742009-09-14 22:02:01 +00004144 RemainingMatches.append(Matches.begin(), Matches.end());
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004145 }
Mike Stump11289f42009-09-09 15:08:12 +00004146
4147 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004148 // selected function.
4149 if (RemainingMatches.size() == 1)
4150 return RemainingMatches.front();
Mike Stump11289f42009-09-09 15:08:12 +00004151
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004152 // FIXME: We should probably return the same thing that BestViableFunction
4153 // returns (even if we issue the diagnostics here).
4154 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4155 << RemainingMatches[0]->getDeclName();
4156 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4157 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004158 return 0;
4159}
4160
Douglas Gregorcabea402009-09-22 15:41:20 +00004161/// \brief Add a single candidate to the overload set.
4162static void AddOverloadedCallCandidate(Sema &S,
4163 AnyFunctionDecl Callee,
4164 bool &ArgumentDependentLookup,
4165 bool HasExplicitTemplateArgs,
4166 const TemplateArgument *ExplicitTemplateArgs,
4167 unsigned NumExplicitTemplateArgs,
4168 Expr **Args, unsigned NumArgs,
4169 OverloadCandidateSet &CandidateSet,
4170 bool PartialOverloading) {
4171 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
4172 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
4173 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4174 PartialOverloading);
4175
4176 if (Func->getDeclContext()->isRecord() ||
4177 Func->getDeclContext()->isFunctionOrMethod())
4178 ArgumentDependentLookup = false;
4179 return;
4180 }
4181
4182 FunctionTemplateDecl *FuncTemplate = cast<FunctionTemplateDecl>(Callee);
4183 S.AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4184 ExplicitTemplateArgs,
4185 NumExplicitTemplateArgs,
4186 Args, NumArgs, CandidateSet);
4187
4188 if (FuncTemplate->getDeclContext()->isRecord())
4189 ArgumentDependentLookup = false;
4190}
4191
4192/// \brief Add the overload candidates named by callee and/or found by argument
4193/// dependent lookup to the given overload set.
4194void Sema::AddOverloadedCallCandidates(NamedDecl *Callee,
4195 DeclarationName &UnqualifiedName,
4196 bool &ArgumentDependentLookup,
4197 bool HasExplicitTemplateArgs,
4198 const TemplateArgument *ExplicitTemplateArgs,
4199 unsigned NumExplicitTemplateArgs,
4200 Expr **Args, unsigned NumArgs,
4201 OverloadCandidateSet &CandidateSet,
4202 bool PartialOverloading) {
4203 // Add the functions denoted by Callee to the set of candidate
4204 // functions. While we're doing so, track whether argument-dependent
4205 // lookup still applies, per:
4206 //
4207 // C++0x [basic.lookup.argdep]p3:
4208 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4209 // and let Y be the lookup set produced by argument dependent
4210 // lookup (defined as follows). If X contains
4211 //
4212 // -- a declaration of a class member, or
4213 //
4214 // -- a block-scope function declaration that is not a
4215 // using-declaration (FIXME: check for using declaration), or
4216 //
4217 // -- a declaration that is neither a function or a function
4218 // template
4219 //
4220 // then Y is empty.
4221 if (!Callee) {
4222 // Nothing to do.
4223 } else if (OverloadedFunctionDecl *Ovl
4224 = dyn_cast<OverloadedFunctionDecl>(Callee)) {
4225 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4226 FuncEnd = Ovl->function_end();
4227 Func != FuncEnd; ++Func)
4228 AddOverloadedCallCandidate(*this, *Func, ArgumentDependentLookup,
4229 HasExplicitTemplateArgs,
4230 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4231 Args, NumArgs, CandidateSet,
4232 PartialOverloading);
4233 } else if (isa<FunctionDecl>(Callee) || isa<FunctionTemplateDecl>(Callee))
4234 AddOverloadedCallCandidate(*this,
4235 AnyFunctionDecl::getFromNamedDecl(Callee),
4236 ArgumentDependentLookup,
4237 HasExplicitTemplateArgs,
4238 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4239 Args, NumArgs, CandidateSet,
4240 PartialOverloading);
4241 // FIXME: assert isa<FunctionDecl> || isa<FunctionTemplateDecl> rather than
4242 // checking dynamically.
4243
4244 if (Callee)
4245 UnqualifiedName = Callee->getDeclName();
4246
4247 if (ArgumentDependentLookup)
4248 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
4249 HasExplicitTemplateArgs,
4250 ExplicitTemplateArgs,
4251 NumExplicitTemplateArgs,
4252 CandidateSet,
4253 PartialOverloading);
4254}
4255
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004256/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00004257/// (which eventually refers to the declaration Func) and the call
4258/// arguments Args/NumArgs, attempt to resolve the function call down
4259/// to a specific function. If overload resolution succeeds, returns
4260/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00004261/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004262/// arguments and Fn, and returns NULL.
Douglas Gregore254f902009-02-04 00:32:51 +00004263FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004264 DeclarationName UnqualifiedName,
Douglas Gregor89026b52009-06-30 23:57:56 +00004265 bool HasExplicitTemplateArgs,
4266 const TemplateArgument *ExplicitTemplateArgs,
4267 unsigned NumExplicitTemplateArgs,
Douglas Gregora60a6912008-11-26 06:01:48 +00004268 SourceLocation LParenLoc,
4269 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004270 SourceLocation *CommaLocs,
Douglas Gregore254f902009-02-04 00:32:51 +00004271 SourceLocation RParenLoc,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004272 bool &ArgumentDependentLookup) {
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004273 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004274
4275 // Add the functions denoted by Callee to the set of candidate
Douglas Gregorcabea402009-09-22 15:41:20 +00004276 // functions.
4277 AddOverloadedCallCandidates(Callee, UnqualifiedName, ArgumentDependentLookup,
4278 HasExplicitTemplateArgs, ExplicitTemplateArgs,
4279 NumExplicitTemplateArgs, Args, NumArgs,
4280 CandidateSet);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004281 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004282 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregora60a6912008-11-26 06:01:48 +00004283 case OR_Success:
4284 return Best->Function;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004285
4286 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00004287 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004288 diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004289 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004290 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4291 break;
4292
4293 case OR_Ambiguous:
4294 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004295 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004296 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4297 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004298
4299 case OR_Deleted:
4300 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4301 << Best->Function->isDeleted()
4302 << UnqualifiedName
4303 << Fn->getSourceRange();
4304 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4305 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004306 }
4307
4308 // Overload resolution failed. Destroy all of the subexpressions and
4309 // return NULL.
4310 Fn->Destroy(Context);
4311 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4312 Args[Arg]->Destroy(Context);
4313 return 0;
4314}
4315
Douglas Gregor084d8552009-03-13 23:49:33 +00004316/// \brief Create a unary operation that may resolve to an overloaded
4317/// operator.
4318///
4319/// \param OpLoc The location of the operator itself (e.g., '*').
4320///
4321/// \param OpcIn The UnaryOperator::Opcode that describes this
4322/// operator.
4323///
4324/// \param Functions The set of non-member functions that will be
4325/// considered by overload resolution. The caller needs to build this
4326/// set based on the context using, e.g.,
4327/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4328/// set should not contain any member functions; those will be added
4329/// by CreateOverloadedUnaryOp().
4330///
4331/// \param input The input argument.
4332Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4333 unsigned OpcIn,
4334 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00004335 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004336 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4337 Expr *Input = (Expr *)input.get();
4338
4339 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4340 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4341 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4342
4343 Expr *Args[2] = { Input, 0 };
4344 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004345
Douglas Gregor084d8552009-03-13 23:49:33 +00004346 // For post-increment and post-decrement, add the implicit '0' as
4347 // the second argument, so that we know this is a post-increment or
4348 // post-decrement.
4349 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4350 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00004351 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00004352 SourceLocation());
4353 NumArgs = 2;
4354 }
4355
4356 if (Input->isTypeDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00004357 OverloadedFunctionDecl *Overloads
Douglas Gregor084d8552009-03-13 23:49:33 +00004358 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004359 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00004360 FuncEnd = Functions.end();
4361 Func != FuncEnd; ++Func)
4362 Overloads->addOverload(*Func);
4363
4364 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4365 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004366
Douglas Gregor084d8552009-03-13 23:49:33 +00004367 input.release();
4368 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4369 &Args[0], NumArgs,
4370 Context.DependentTy,
4371 OpLoc));
4372 }
4373
4374 // Build an empty overload set.
4375 OverloadCandidateSet CandidateSet;
4376
4377 // Add the candidates from the given function set.
4378 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4379
4380 // Add operator candidates that are member functions.
4381 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4382
4383 // Add builtin operator candidates.
4384 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4385
4386 // Perform overload resolution.
4387 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004388 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004389 case OR_Success: {
4390 // We found a built-in operator or an overloaded operator.
4391 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00004392
Douglas Gregor084d8552009-03-13 23:49:33 +00004393 if (FnDecl) {
4394 // We matched an overloaded operator. Build a call to that
4395 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00004396
Douglas Gregor084d8552009-03-13 23:49:33 +00004397 // Convert the arguments.
4398 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4399 if (PerformObjectArgumentInitialization(Input, Method))
4400 return ExprError();
4401 } else {
4402 // Convert the arguments.
4403 if (PerformCopyInitialization(Input,
4404 FnDecl->getParamDecl(0)->getType(),
4405 "passing"))
4406 return ExprError();
4407 }
4408
4409 // Determine the result type
4410 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00004411 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor084d8552009-03-13 23:49:33 +00004412 ResultTy = ResultTy.getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004413
Douglas Gregor084d8552009-03-13 23:49:33 +00004414 // Build the actual expression node.
4415 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4416 SourceLocation());
4417 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004418
Douglas Gregor084d8552009-03-13 23:49:33 +00004419 input.release();
Mike Stump11289f42009-09-09 15:08:12 +00004420
4421 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlssone80ccac2009-08-16 04:11:06 +00004422 &Input, 1, ResultTy, OpLoc);
4423 return MaybeBindToTemporary(CE);
Douglas Gregor084d8552009-03-13 23:49:33 +00004424 } else {
4425 // We matched a built-in operator. Convert the arguments, then
4426 // break out so that we will build the appropriate built-in
4427 // operator node.
4428 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4429 Best->Conversions[0], "passing"))
4430 return ExprError();
4431
4432 break;
4433 }
4434 }
4435
4436 case OR_No_Viable_Function:
4437 // No viable function; fall through to handling this as a
4438 // built-in operator, which will produce an error message for us.
4439 break;
4440
4441 case OR_Ambiguous:
4442 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4443 << UnaryOperator::getOpcodeStr(Opc)
4444 << Input->getSourceRange();
4445 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4446 return ExprError();
4447
4448 case OR_Deleted:
4449 Diag(OpLoc, diag::err_ovl_deleted_oper)
4450 << Best->Function->isDeleted()
4451 << UnaryOperator::getOpcodeStr(Opc)
4452 << Input->getSourceRange();
4453 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4454 return ExprError();
4455 }
4456
4457 // Either we found no viable overloaded operator or we matched a
4458 // built-in operator. In either case, fall through to trying to
4459 // build a built-in operation.
4460 input.release();
4461 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4462}
4463
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004464/// \brief Create a binary operation that may resolve to an overloaded
4465/// operator.
4466///
4467/// \param OpLoc The location of the operator itself (e.g., '+').
4468///
4469/// \param OpcIn The BinaryOperator::Opcode that describes this
4470/// operator.
4471///
4472/// \param Functions The set of non-member functions that will be
4473/// considered by overload resolution. The caller needs to build this
4474/// set based on the context using, e.g.,
4475/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4476/// set should not contain any member functions; those will be added
4477/// by CreateOverloadedBinOp().
4478///
4479/// \param LHS Left-hand argument.
4480/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00004481Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004482Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004483 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004484 FunctionSet &Functions,
4485 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004486 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00004487 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004488
4489 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4490 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4491 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4492
4493 // If either side is type-dependent, create an appropriate dependent
4494 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00004495 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004496 // .* cannot be overloaded.
4497 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004498 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004499 Context.DependentTy, OpLoc));
4500
Mike Stump11289f42009-09-09 15:08:12 +00004501 OverloadedFunctionDecl *Overloads
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004502 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004503 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004504 FuncEnd = Functions.end();
4505 Func != FuncEnd; ++Func)
4506 Overloads->addOverload(*Func);
4507
4508 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4509 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004510
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004511 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00004512 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004513 Context.DependentTy,
4514 OpLoc));
4515 }
4516
4517 // If this is the .* operator, which is not overloadable, just
4518 // create a built-in binary operator.
4519 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004520 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004521
4522 // If this is one of the assignment operators, we only perform
4523 // overload resolution if the left-hand side is a class or
4524 // enumeration type (C++ [expr.ass]p3).
4525 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregore9899d92009-08-26 17:08:25 +00004526 !Args[0]->getType()->isOverloadableType())
4527 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004528
Douglas Gregor084d8552009-03-13 23:49:33 +00004529 // Build an empty overload set.
4530 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004531
4532 // Add the candidates from the given function set.
4533 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4534
4535 // Add operator candidates that are member functions.
4536 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4537
4538 // Add builtin operator candidates.
4539 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4540
4541 // Perform overload resolution.
4542 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004543 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004544 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004545 // We found a built-in operator or an overloaded operator.
4546 FunctionDecl *FnDecl = Best->Function;
4547
4548 if (FnDecl) {
4549 // We matched an overloaded operator. Build a call to that
4550 // operator.
4551
4552 // Convert the arguments.
4553 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregore9899d92009-08-26 17:08:25 +00004554 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4555 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004556 "passing"))
4557 return ExprError();
4558 } else {
4559 // Convert the arguments.
Douglas Gregore9899d92009-08-26 17:08:25 +00004560 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004561 "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004562 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004563 "passing"))
4564 return ExprError();
4565 }
4566
4567 // Determine the result type
4568 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00004569 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004570 ResultTy = ResultTy.getNonReferenceType();
4571
4572 // Build the actual expression node.
4573 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00004574 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004575 UsualUnaryConversions(FnExpr);
4576
Mike Stump11289f42009-09-09 15:08:12 +00004577 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlssone80ccac2009-08-16 04:11:06 +00004578 Args, 2, ResultTy, OpLoc);
4579 return MaybeBindToTemporary(CE);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004580 } else {
4581 // We matched a built-in operator. Convert the arguments, then
4582 // break out so that we will build the appropriate built-in
4583 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00004584 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004585 Best->Conversions[0], "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004586 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004587 Best->Conversions[1], "passing"))
4588 return ExprError();
4589
4590 break;
4591 }
4592 }
4593
4594 case OR_No_Viable_Function:
Sebastian Redl027de2a2009-05-21 11:50:50 +00004595 // For class as left operand for assignment or compound assigment operator
4596 // do not fall through to handling in built-in, but report that no overloaded
4597 // assignment operator found
Douglas Gregore9899d92009-08-26 17:08:25 +00004598 if (Args[0]->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00004599 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4600 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004601 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Sebastian Redl027de2a2009-05-21 11:50:50 +00004602 return ExprError();
4603 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004604 // No viable function; fall through to handling this as a
4605 // built-in operator, which will produce an error message for us.
4606 break;
4607
4608 case OR_Ambiguous:
4609 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4610 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004611 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004612 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4613 return ExprError();
4614
4615 case OR_Deleted:
4616 Diag(OpLoc, diag::err_ovl_deleted_oper)
4617 << Best->Function->isDeleted()
4618 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004619 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004620 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4621 return ExprError();
4622 }
4623
4624 // Either we found no viable overloaded operator or we matched a
4625 // built-in operator. In either case, try to build a built-in
4626 // operation.
Douglas Gregore9899d92009-08-26 17:08:25 +00004627 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004628}
4629
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004630/// BuildCallToMemberFunction - Build a call to a member
4631/// function. MemExpr is the expression that refers to the member
4632/// function (and includes the object parameter), Args/NumArgs are the
4633/// arguments to the function call (not including the object
4634/// parameter). The caller needs to validate that the member
4635/// expression refers to a member function or an overloaded member
4636/// function.
4637Sema::ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00004638Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4639 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004640 unsigned NumArgs, SourceLocation *CommaLocs,
4641 SourceLocation RParenLoc) {
4642 // Dig out the member expression. This holds both the object
4643 // argument and the member function we're referring to.
4644 MemberExpr *MemExpr = 0;
4645 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4646 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4647 else
4648 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4649 assert(MemExpr && "Building member call without member expression");
4650
4651 // Extract the object argument.
4652 Expr *ObjectArg = MemExpr->getBase();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004653
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004654 CXXMethodDecl *Method = 0;
Douglas Gregor97628d62009-08-21 00:16:32 +00004655 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4656 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004657 // Add overload candidates
4658 OverloadCandidateSet CandidateSet;
Douglas Gregor97628d62009-08-21 00:16:32 +00004659 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004660
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004661 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4662 Func != FuncEnd; ++Func) {
4663 if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
Mike Stump11289f42009-09-09 15:08:12 +00004664 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004665 /*SuppressUserConversions=*/false);
4666 else
Douglas Gregor84f14dd2009-09-01 00:37:14 +00004667 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4668 MemExpr->hasExplicitTemplateArgumentList(),
4669 MemExpr->getTemplateArgs(),
4670 MemExpr->getNumTemplateArgs(),
4671 ObjectArg, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004672 CandidateSet,
4673 /*SuppressUsedConversions=*/false);
4674 }
Mike Stump11289f42009-09-09 15:08:12 +00004675
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004676 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004677 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004678 case OR_Success:
4679 Method = cast<CXXMethodDecl>(Best->Function);
4680 break;
4681
4682 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00004683 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004684 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00004685 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004686 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4687 // FIXME: Leaking incoming expressions!
4688 return true;
4689
4690 case OR_Ambiguous:
Mike Stump11289f42009-09-09 15:08:12 +00004691 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004692 diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00004693 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004694 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4695 // FIXME: Leaking incoming expressions!
4696 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004697
4698 case OR_Deleted:
Mike Stump11289f42009-09-09 15:08:12 +00004699 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00004700 diag::err_ovl_deleted_member_call)
4701 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00004702 << DeclName << MemExprE->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00004703 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4704 // FIXME: Leaking incoming expressions!
4705 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004706 }
4707
4708 FixOverloadedFunctionReference(MemExpr, Method);
4709 } else {
4710 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4711 }
4712
4713 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00004714 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004715 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
Mike Stump11289f42009-09-09 15:08:12 +00004716 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004717 Method->getResultType().getNonReferenceType(),
4718 RParenLoc));
4719
4720 // Convert the object argument (for a non-static member function call).
Mike Stump11289f42009-09-09 15:08:12 +00004721 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004722 PerformObjectArgumentInitialization(ObjectArg, Method))
4723 return true;
4724 MemExpr->setBase(ObjectArg);
4725
4726 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004727 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004728 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004729 RParenLoc))
4730 return true;
4731
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004732 if (CheckFunctionCall(Method, TheCall.get()))
4733 return true;
Anders Carlsson8c84c202009-08-16 03:42:12 +00004734
4735 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004736}
4737
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004738/// BuildCallToObjectOfClassType - Build a call to an object of class
4739/// type (C++ [over.call.object]), which can end up invoking an
4740/// overloaded function call operator (@c operator()) or performing a
4741/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00004742Sema::ExprResult
4743Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00004744 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004745 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004746 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004747 SourceLocation RParenLoc) {
4748 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004749 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00004750
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004751 // C++ [over.call.object]p1:
4752 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00004753 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004754 // candidate functions includes at least the function call
4755 // operators of T. The function call operators of T are obtained by
4756 // ordinary lookup of the name operator() in the context of
4757 // (E).operator().
4758 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00004759 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor55297ac2008-12-23 00:26:44 +00004760 DeclContext::lookup_const_iterator Oper, OperEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004761 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor55297ac2008-12-23 00:26:44 +00004762 Oper != OperEnd; ++Oper)
Mike Stump11289f42009-09-09 15:08:12 +00004763 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
Douglas Gregor55297ac2008-12-23 00:26:44 +00004764 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004765
Douglas Gregorab7897a2008-11-19 22:57:39 +00004766 // C++ [over.call.object]p2:
4767 // In addition, for each conversion function declared in T of the
4768 // form
4769 //
4770 // operator conversion-type-id () cv-qualifier;
4771 //
4772 // where cv-qualifier is the same cv-qualification as, or a
4773 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00004774 // denotes the type "pointer to function of (P1,...,Pn) returning
4775 // R", or the type "reference to pointer to function of
4776 // (P1,...,Pn) returning R", or the type "reference to function
4777 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00004778 // is also considered as a candidate function. Similarly,
4779 // surrogate call functions are added to the set of candidate
4780 // functions for each conversion function declared in an
4781 // accessible base class provided the function is not hidden
4782 // within T by another intervening declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004783
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004784 if (!RequireCompleteType(SourceLocation(), Object->getType(), 0)) {
4785 // FIXME: Look in base classes for more conversion operators!
Mike Stump11289f42009-09-09 15:08:12 +00004786 OverloadedFunctionDecl *Conversions
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004787 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00004788 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004789 Func = Conversions->function_begin(),
4790 FuncEnd = Conversions->function_end();
4791 Func != FuncEnd; ++Func) {
4792 CXXConversionDecl *Conv;
4793 FunctionTemplateDecl *ConvTemplate;
4794 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Douglas Gregor05155d82009-08-21 23:19:43 +00004795
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004796 // Skip over templated conversion functions; they aren't
4797 // surrogates.
4798 if (ConvTemplate)
4799 continue;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004800
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004801 // Strip the reference type (if any) and then the pointer type (if
4802 // any) to get down to what might be a function type.
4803 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4804 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4805 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004806
John McCall9dd450b2009-09-21 23:43:11 +00004807 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004808 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4809 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00004810 }
Mike Stump11289f42009-09-09 15:08:12 +00004811
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004812 // Perform overload resolution.
4813 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004814 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004815 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00004816 // Overload resolution succeeded; we'll build the appropriate call
4817 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004818 break;
4819
4820 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00004821 Diag(Object->getSourceRange().getBegin(),
Sebastian Redl15b02d22008-11-22 13:44:36 +00004822 diag::err_ovl_no_viable_object_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004823 << Object->getType() << Object->getSourceRange();
Sebastian Redl15b02d22008-11-22 13:44:36 +00004824 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004825 break;
4826
4827 case OR_Ambiguous:
4828 Diag(Object->getSourceRange().getBegin(),
4829 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004830 << Object->getType() << Object->getSourceRange();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004831 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4832 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004833
4834 case OR_Deleted:
4835 Diag(Object->getSourceRange().getBegin(),
4836 diag::err_ovl_deleted_object_call)
4837 << Best->Function->isDeleted()
4838 << Object->getType() << Object->getSourceRange();
4839 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4840 break;
Mike Stump11289f42009-09-09 15:08:12 +00004841 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004842
Douglas Gregorab7897a2008-11-19 22:57:39 +00004843 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004844 // We had an error; delete all of the subexpressions and return
4845 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00004846 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004847 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00004848 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004849 return true;
4850 }
4851
Douglas Gregorab7897a2008-11-19 22:57:39 +00004852 if (Best->Function == 0) {
4853 // Since there is no function declaration, this is one of the
4854 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00004855 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00004856 = cast<CXXConversionDecl>(
4857 Best->Conversions[0].UserDefined.ConversionFunction);
4858
4859 // We selected one of the surrogate functions that converts the
4860 // object parameter to a function pointer. Perform the conversion
4861 // on the object argument, then let ActOnCallExpr finish the job.
4862 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004863 ImpCastExprToType(Object,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004864 Conv->getConversionType().getNonReferenceType(),
Anders Carlssona076d142009-07-31 01:23:52 +00004865 CastExpr::CK_Unknown,
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004866 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004867 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4868 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4869 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004870 }
4871
4872 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4873 // that calls this method, using Object for the implicit object
4874 // parameter and passing along the remaining arguments.
4875 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00004876 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004877
4878 unsigned NumArgsInProto = Proto->getNumArgs();
4879 unsigned NumArgsToCheck = NumArgs;
4880
4881 // Build the full argument list for the method call (the
4882 // implicit object parameter is placed at the beginning of the
4883 // list).
4884 Expr **MethodArgs;
4885 if (NumArgs < NumArgsInProto) {
4886 NumArgsToCheck = NumArgsInProto;
4887 MethodArgs = new Expr*[NumArgsInProto + 1];
4888 } else {
4889 MethodArgs = new Expr*[NumArgs + 1];
4890 }
4891 MethodArgs[0] = Object;
4892 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4893 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00004894
4895 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004896 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004897 UsualUnaryConversions(NewFn);
4898
4899 // Once we've built TheCall, all of the expressions are properly
4900 // owned.
4901 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004902 ExprOwningPtr<CXXOperatorCallExpr>
4903 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004904 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00004905 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004906 delete [] MethodArgs;
4907
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004908 // We may have default arguments. If so, we need to allocate more
4909 // slots in the call for them.
4910 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00004911 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004912 else if (NumArgs > NumArgsInProto)
4913 NumArgsToCheck = NumArgsInProto;
4914
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004915 bool IsError = false;
4916
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004917 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004918 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004919 TheCall->setArg(0, Object);
4920
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004921
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004922 // Check the argument types.
4923 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004924 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004925 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004926 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00004927
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004928 // Pass the argument.
4929 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004930 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004931 } else {
Anders Carlssone8271232009-08-14 18:30:22 +00004932 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregor02a0acd2009-01-13 05:10:00 +00004933 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004934
4935 TheCall->setArg(i + 1, Arg);
4936 }
4937
4938 // If this is a variadic call, handle args passed through "...".
4939 if (Proto->isVariadic()) {
4940 // Promote the arguments (C99 6.5.2.2p7).
4941 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4942 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004943 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004944 TheCall->setArg(i + 1, Arg);
4945 }
4946 }
4947
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00004948 if (IsError) return true;
4949
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004950 if (CheckFunctionCall(Method, TheCall.get()))
4951 return true;
4952
Anders Carlsson1c83deb2009-08-16 03:53:54 +00004953 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004954}
4955
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004956/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00004957/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004958/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00004959Sema::OwningExprResult
4960Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
4961 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004962 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00004963
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004964 // C++ [over.ref]p1:
4965 //
4966 // [...] An expression x->m is interpreted as (x.operator->())->m
4967 // for a class object x of type T if T::operator->() exists and if
4968 // the operator is selected as the best match function by the
4969 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004970 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4971 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004972 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00004973
Anders Carlsson78b54932009-09-10 23:18:36 +00004974 LookupResult R = LookupQualifiedName(BaseRecord->getDecl(), OpName,
4975 LookupOrdinaryName);
4976
4977 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
4978 Oper != OperEnd; ++Oper)
Douglas Gregor55297ac2008-12-23 00:26:44 +00004979 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004980 /*SuppressUserConversions=*/false);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004981
4982 // Perform overload resolution.
4983 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004984 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004985 case OR_Success:
4986 // Overload resolution succeeded; we'll build the call below.
4987 break;
4988
4989 case OR_No_Viable_Function:
4990 if (CandidateSet.empty())
4991 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00004992 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004993 else
4994 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00004995 << "operator->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004996 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregord8061562009-08-06 03:17:00 +00004997 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00004998
4999 case OR_Ambiguous:
5000 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00005001 << "->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005002 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005003 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005004
5005 case OR_Deleted:
5006 Diag(OpLoc, diag::err_ovl_deleted_oper)
5007 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00005008 << "->" << Base->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005009 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005010 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005011 }
5012
5013 // Convert the object parameter.
5014 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00005015 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00005016 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00005017
5018 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00005019 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005020
5021 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00005022 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5023 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005024 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005025 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005026 Method->getResultType().getNonReferenceType(),
5027 OpLoc);
Douglas Gregord8061562009-08-06 03:17:00 +00005028 return Owned(Base);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005029}
5030
Douglas Gregorcd695e52008-11-10 20:40:00 +00005031/// FixOverloadedFunctionReference - E is an expression that refers to
5032/// a C++ overloaded function (possibly with some parentheses and
5033/// perhaps a '&' around it). We have resolved the overloaded function
5034/// to the function declaration Fn, so patch up the expression E to
5035/// refer (possibly indirectly) to Fn.
5036void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
5037 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5038 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5039 E->setType(PE->getSubExpr()->getType());
5040 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00005041 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00005042 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005043 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5044 if (Method->isStatic()) {
5045 // Do nothing: static member functions aren't any different
5046 // from non-member functions.
Mike Stump11289f42009-09-09 15:08:12 +00005047 } else if (QualifiedDeclRefExpr *DRE
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005048 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
5049 // We have taken the address of a pointer to member
5050 // function. Perform the computation here so that we get the
5051 // appropriate pointer to member type.
5052 DRE->setDecl(Fn);
5053 DRE->setType(Fn->getType());
5054 QualType ClassType
5055 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
Mike Stump11289f42009-09-09 15:08:12 +00005056 E->setType(Context.getMemberPointerType(Fn->getType(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005057 ClassType.getTypePtr()));
5058 return;
5059 }
5060 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005061 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005062 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregorcd695e52008-11-10 20:40:00 +00005063 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor9b146582009-07-08 20:55:45 +00005064 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
Mike Stump11289f42009-09-09 15:08:12 +00005065 isa<FunctionTemplateDecl>(DR->getDecl())) &&
Douglas Gregor9b146582009-07-08 20:55:45 +00005066 "Expected overloaded function or function template");
Douglas Gregorcd695e52008-11-10 20:40:00 +00005067 DR->setDecl(Fn);
5068 E->setType(Fn->getType());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005069 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
5070 MemExpr->setMemberDecl(Fn);
5071 E->setType(Fn->getType());
Douglas Gregorcd695e52008-11-10 20:40:00 +00005072 } else {
5073 assert(false && "Invalid reference to overloaded function");
5074 }
5075}
5076
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005077} // end namespace clang