blob: c69e2d50ea1f036227b16e75b6f49f6c1741ce62 [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"
15#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000016#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#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.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000407/// If @p UserCast, the implicit conversion is being done for a user-specified
408/// cast.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000409ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000410Sema::TryImplicitConversion(Expr* From, QualType ToType,
411 bool SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +0000412 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000413 bool InOverloadResolution,
414 bool UserCast) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000415 ImplicitConversionSequence ICS;
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000416 OverloadCandidateSet Conversions;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000417 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson228eea32009-08-28 15:33:32 +0000418 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000419 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000420 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000421 (UserDefResult = IsUserDefinedConversion(From, ToType,
422 ICS.UserDefined,
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000423 Conversions,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000424 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000425 ForceRValue, UserCast)) == OR_Success) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000426 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor05379422008-11-03 17:51:48 +0000427 // C++ [over.ics.user]p4:
428 // A conversion of an expression of class type to the same class
429 // type is given Exact Match rank, and a conversion of an
430 // expression of class type to a base class of that type is
431 // given Conversion rank, in spite of the fact that a copy
432 // constructor (i.e., a user-defined conversion function) is
433 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000434 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000435 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000436 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000437 = Context.getCanonicalType(From->getType().getUnqualifiedType());
438 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
439 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000440 // Turn this into a "standard" conversion sequence, so that it
441 // gets ranked with standard conversion sequences.
Douglas Gregor05379422008-11-03 17:51:48 +0000442 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
443 ICS.Standard.setAsIdentityConversion();
444 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
445 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000446 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000447 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000448 ICS.Standard.Second = ICK_Derived_To_Base;
449 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000450 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000451
452 // C++ [over.best.ics]p4:
453 // However, when considering the argument of a user-defined
454 // conversion function that is a candidate by 13.3.1.3 when
455 // invoked for the copying of the temporary in the second step
456 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
457 // 13.3.1.6 in all cases, only standard conversion sequences and
458 // ellipsis conversion sequences are allowed.
459 if (SuppressUserConversions &&
460 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
461 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000462 } else {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000463 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000464 if (UserDefResult == OR_Ambiguous) {
465 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
466 Cand != Conversions.end(); ++Cand)
Fariborz Jahanian574de2c2009-10-12 17:51:19 +0000467 if (Cand->Viable)
468 ICS.ConversionFunctionSet.push_back(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000469 }
470 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000471
472 return ICS;
473}
474
475/// IsStandardConversion - Determines whether there is a standard
476/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
477/// expression From to the type ToType. Standard conversion sequences
478/// only consider non-class types; for conversions that involve class
479/// types, use TryImplicitConversion. If a conversion exists, SCS will
480/// contain the standard conversion sequence required to perform this
481/// conversion and this routine will return true. Otherwise, this
482/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000483bool
484Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000485 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000486 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000487 QualType FromType = From->getType();
488
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000489 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000490 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000491 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000492 SCS.IncompatibleObjC = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000493 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000494 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000495
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000496 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000497 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000498 if (FromType->isRecordType() || ToType->isRecordType()) {
499 if (getLangOptions().CPlusPlus)
500 return false;
501
Mike Stump11289f42009-09-09 15:08:12 +0000502 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000503 }
504
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000505 // The first conversion can be an lvalue-to-rvalue conversion,
506 // array-to-pointer conversion, or function-to-pointer conversion
507 // (C++ 4p1).
508
Mike Stump11289f42009-09-09 15:08:12 +0000509 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000510 // An lvalue (3.10) of a non-function, non-array type T can be
511 // converted to an rvalue.
512 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000513 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000514 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000515 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000516 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000517
518 // If T is a non-class type, the type of the rvalue is the
519 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000520 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
521 // just strip the qualifiers because they don't matter.
522
523 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000524 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000525 } else if (FromType->isArrayType()) {
526 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000527 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000528
529 // An lvalue or rvalue of type "array of N T" or "array of unknown
530 // bound of T" can be converted to an rvalue of type "pointer to
531 // T" (C++ 4.2p1).
532 FromType = Context.getArrayDecayedType(FromType);
533
534 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
535 // This conversion is deprecated. (C++ D.4).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000536 SCS.Deprecated = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000537
538 // For the purpose of ranking in overload resolution
539 // (13.3.3.1.1), this conversion is considered an
540 // array-to-pointer conversion followed by a qualification
541 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000542 SCS.Second = ICK_Identity;
543 SCS.Third = ICK_Qualification;
544 SCS.ToTypePtr = ToType.getAsOpaquePtr();
545 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000546 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000547 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
548 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000549 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000550
551 // An lvalue of function type T can be converted to an rvalue of
552 // type "pointer to T." The result is a pointer to the
553 // function. (C++ 4.3p1).
554 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000555 } else if (FunctionDecl *Fn
Douglas Gregorcd695e52008-11-10 20:40:00 +0000556 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000557 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000558 SCS.First = ICK_Function_To_Pointer;
559
560 // We were able to resolve the address of the overloaded function,
561 // so we can convert to the type of that function.
562 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000563 if (ToType->isLValueReferenceType())
564 FromType = Context.getLValueReferenceType(FromType);
565 else if (ToType->isRValueReferenceType())
566 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000567 else if (ToType->isMemberPointerType()) {
568 // Resolve address only succeeds if both sides are member pointers,
569 // but it doesn't have to be the same class. See DR 247.
570 // Note that this means that the type of &Derived::fn can be
571 // Ret (Base::*)(Args) if the fn overload actually found is from the
572 // base class, even if it was brought into the derived class via a
573 // using declaration. The standard isn't clear on this issue at all.
574 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
575 FromType = Context.getMemberPointerType(FromType,
576 Context.getTypeDeclType(M->getParent()).getTypePtr());
577 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000578 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000579 } else {
580 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000581 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000582 }
583
584 // The second conversion can be an integral promotion, floating
585 // point promotion, integral conversion, floating point conversion,
586 // floating-integral conversion, pointer conversion,
587 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000588 // For overloading in C, this can also be a "compatible-type"
589 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000590 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000591 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000592 // The unqualified versions of the types are the same: there's no
593 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000594 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000595 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000596 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000597 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000598 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000599 } else if (IsFloatingPointPromotion(FromType, ToType)) {
600 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000601 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000602 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000603 } else if (IsComplexPromotion(FromType, ToType)) {
604 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000605 SCS.Second = ICK_Complex_Promotion;
606 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000607 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000608 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000609 // Integral conversions (C++ 4.7).
610 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000611 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000612 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000613 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
614 // Floating point conversions (C++ 4.8).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000615 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000616 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000617 } else if (FromType->isComplexType() && ToType->isComplexType()) {
618 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000619 SCS.Second = ICK_Complex_Conversion;
620 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000621 } else if ((FromType->isFloatingType() &&
622 ToType->isIntegralType() && (!ToType->isBooleanType() &&
623 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000624 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000625 ToType->isFloatingType())) {
626 // Floating-integral conversions (C++ 4.9).
627 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000628 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000629 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000630 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
631 (ToType->isComplexType() && FromType->isArithmeticType())) {
632 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000633 SCS.Second = ICK_Complex_Real;
634 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000635 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
636 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000637 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000638 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000639 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000640 } else if (IsMemberPointerConversion(From, FromType, ToType,
641 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000642 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000643 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000644 } else if (ToType->isBooleanType() &&
645 (FromType->isArithmeticType() ||
646 FromType->isEnumeralType() ||
647 FromType->isPointerType() ||
648 FromType->isBlockPointerType() ||
649 FromType->isMemberPointerType() ||
650 FromType->isNullPtrType())) {
651 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000652 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000653 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000654 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000655 Context.typesAreCompatible(ToType, FromType)) {
656 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000657 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000658 } else {
659 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000660 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000661 }
662
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000663 QualType CanonFrom;
664 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000665 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000666 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000667 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000668 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000669 CanonFrom = Context.getCanonicalType(FromType);
670 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000671 } else {
672 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000673 SCS.Third = ICK_Identity;
674
Mike Stump11289f42009-09-09 15:08:12 +0000675 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000676 // [...] Any difference in top-level cv-qualification is
677 // subsumed by the initialization itself and does not constitute
678 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000679 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000680 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000681 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000682 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
683 FromType = ToType;
684 CanonFrom = CanonTo;
685 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000686 }
687
688 // If we have not converted the argument type to the parameter type,
689 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000690 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000691 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000692
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000693 SCS.ToTypePtr = FromType.getAsOpaquePtr();
694 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000695}
696
697/// IsIntegralPromotion - Determines whether the conversion from the
698/// expression From (whose potentially-adjusted type is FromType) to
699/// ToType is an integral promotion (C++ 4.5). If so, returns true and
700/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000701bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000702 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000703 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000704 if (!To) {
705 return false;
706 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000707
708 // An rvalue of type char, signed char, unsigned char, short int, or
709 // unsigned short int can be converted to an rvalue of type int if
710 // int can represent all the values of the source type; otherwise,
711 // the source rvalue can be converted to an rvalue of type unsigned
712 // int (C++ 4.5p1).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000713 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000714 if (// We can promote any signed, promotable integer type to an int
715 (FromType->isSignedIntegerType() ||
716 // We can promote any unsigned integer type whose size is
717 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000718 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000719 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000720 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000721 }
722
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000723 return To->getKind() == BuiltinType::UInt;
724 }
725
726 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
727 // can be converted to an rvalue of the first of the following types
728 // that can represent all the values of its underlying type: int,
729 // unsigned int, long, or unsigned long (C++ 4.5p2).
730 if ((FromType->isEnumeralType() || FromType->isWideCharType())
731 && ToType->isIntegerType()) {
732 // Determine whether the type we're converting from is signed or
733 // unsigned.
734 bool FromIsSigned;
735 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall9dd450b2009-09-21 23:43:11 +0000736 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000737 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
738 FromIsSigned = UnderlyingType->isSignedIntegerType();
739 } else {
740 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
741 FromIsSigned = true;
742 }
743
744 // The types we'll try to promote to, in the appropriate
745 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000746 QualType PromoteTypes[6] = {
747 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000748 Context.LongTy, Context.UnsignedLongTy ,
749 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000750 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000751 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000752 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
753 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000754 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000755 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
756 // We found the type that we can promote to. If this is the
757 // type we wanted, we have a promotion. Otherwise, no
758 // promotion.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000759 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000760 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
761 }
762 }
763 }
764
765 // An rvalue for an integral bit-field (9.6) can be converted to an
766 // rvalue of type int if int can represent all the values of the
767 // bit-field; otherwise, it can be converted to unsigned int if
768 // unsigned int can represent all the values of the bit-field. If
769 // the bit-field is larger yet, no integral promotion applies to
770 // it. If the bit-field has an enumerated type, it is treated as any
771 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000772 // FIXME: We should delay checking of bit-fields until we actually perform the
773 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000774 using llvm::APSInt;
775 if (From)
776 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000777 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000778 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
779 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
780 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
781 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000782
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000783 // Are we promoting to an int from a bitfield that fits in an int?
784 if (BitWidth < ToSize ||
785 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
786 return To->getKind() == BuiltinType::Int;
787 }
Mike Stump11289f42009-09-09 15:08:12 +0000788
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000789 // Are we promoting to an unsigned int from an unsigned bitfield
790 // that fits into an unsigned int?
791 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
792 return To->getKind() == BuiltinType::UInt;
793 }
Mike Stump11289f42009-09-09 15:08:12 +0000794
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000795 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000796 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000797 }
Mike Stump11289f42009-09-09 15:08:12 +0000798
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000799 // An rvalue of type bool can be converted to an rvalue of type int,
800 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000801 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000802 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000803 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000804
805 return false;
806}
807
808/// IsFloatingPointPromotion - Determines whether the conversion from
809/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
810/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000811bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000812 /// An rvalue of type float can be converted to an rvalue of type
813 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000814 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
815 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000816 if (FromBuiltin->getKind() == BuiltinType::Float &&
817 ToBuiltin->getKind() == BuiltinType::Double)
818 return true;
819
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000820 // C99 6.3.1.5p1:
821 // When a float is promoted to double or long double, or a
822 // double is promoted to long double [...].
823 if (!getLangOptions().CPlusPlus &&
824 (FromBuiltin->getKind() == BuiltinType::Float ||
825 FromBuiltin->getKind() == BuiltinType::Double) &&
826 (ToBuiltin->getKind() == BuiltinType::LongDouble))
827 return true;
828 }
829
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000830 return false;
831}
832
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000833/// \brief Determine if a conversion is a complex promotion.
834///
835/// A complex promotion is defined as a complex -> complex conversion
836/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000837/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000838bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000839 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000840 if (!FromComplex)
841 return false;
842
John McCall9dd450b2009-09-21 23:43:11 +0000843 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000844 if (!ToComplex)
845 return false;
846
847 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000848 ToComplex->getElementType()) ||
849 IsIntegralPromotion(0, FromComplex->getElementType(),
850 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000851}
852
Douglas Gregor237f96c2008-11-26 23:31:11 +0000853/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
854/// the pointer type FromPtr to a pointer to type ToPointee, with the
855/// same type qualifiers as FromPtr has on its pointee type. ToType,
856/// if non-empty, will be a pointer to ToType that may or may not have
857/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000858static QualType
859BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000860 QualType ToPointee, QualType ToType,
861 ASTContext &Context) {
862 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
863 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000864 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000865
866 // Exact qualifier match -> return the pointer type we're converting to.
John McCall8ccfcb52009-09-24 19:53:00 +0000867 if (CanonToPointee.getQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000868 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000869 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000870 return ToType;
871
872 // Build a pointer to ToPointee. It has the right qualifiers
873 // already.
874 return Context.getPointerType(ToPointee);
875 }
876
877 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000878 return Context.getPointerType(
879 Context.getQualifiedType(CanonToPointee.getUnqualifiedType(), Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000880}
881
Mike Stump11289f42009-09-09 15:08:12 +0000882static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000883 bool InOverloadResolution,
884 ASTContext &Context) {
885 // Handle value-dependent integral null pointer constants correctly.
886 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
887 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
888 Expr->getType()->isIntegralType())
889 return !InOverloadResolution;
890
Douglas Gregor56751b52009-09-25 04:25:58 +0000891 return Expr->isNullPointerConstant(Context,
892 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
893 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +0000894}
Mike Stump11289f42009-09-09 15:08:12 +0000895
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000896/// IsPointerConversion - Determines whether the conversion of the
897/// expression From, which has the (possibly adjusted) type FromType,
898/// can be converted to the type ToType via a pointer conversion (C++
899/// 4.10). If so, returns true and places the converted type (that
900/// might differ from ToType in its cv-qualifiers at some level) into
901/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000902///
Douglas Gregora29dc052008-11-27 01:19:21 +0000903/// This routine also supports conversions to and from block pointers
904/// and conversions with Objective-C's 'id', 'id<protocols...>', and
905/// pointers to interfaces. FIXME: Once we've determined the
906/// appropriate overloading rules for Objective-C, we may want to
907/// split the Objective-C checks into a different routine; however,
908/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000909/// conversions, so for now they live here. IncompatibleObjC will be
910/// set if the conversion is an allowed Objective-C conversion that
911/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000912bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000913 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000914 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +0000915 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +0000916 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +0000917 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
918 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000919
Mike Stump11289f42009-09-09 15:08:12 +0000920 // Conversion from a null pointer constant to any Objective-C pointer type.
921 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000922 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +0000923 ConvertedType = ToType;
924 return true;
925 }
926
Douglas Gregor231d1c62008-11-27 00:15:41 +0000927 // Blocks: Block pointers can be converted to void*.
928 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000929 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000930 ConvertedType = ToType;
931 return true;
932 }
933 // Blocks: A null pointer constant can be converted to a block
934 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +0000935 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000936 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000937 ConvertedType = ToType;
938 return true;
939 }
940
Sebastian Redl576fd422009-05-10 18:38:11 +0000941 // If the left-hand-side is nullptr_t, the right side can be a null
942 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000943 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000944 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +0000945 ConvertedType = ToType;
946 return true;
947 }
948
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000949 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000950 if (!ToTypePtr)
951 return false;
952
953 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +0000954 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000955 ConvertedType = ToType;
956 return true;
957 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000958
Douglas Gregor237f96c2008-11-26 23:31:11 +0000959 // Beyond this point, both types need to be pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000960 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +0000961 if (!FromTypePtr)
962 return false;
963
964 QualType FromPointeeType = FromTypePtr->getPointeeType();
965 QualType ToPointeeType = ToTypePtr->getPointeeType();
966
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000967 // An rvalue of type "pointer to cv T," where T is an object type,
968 // can be converted to an rvalue of type "pointer to cv void" (C++
969 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +0000970 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000971 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +0000972 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000973 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000974 return true;
975 }
976
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000977 // When we're overloading in C, we allow a special kind of pointer
978 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +0000979 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000980 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000981 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000982 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +0000983 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000984 return true;
985 }
986
Douglas Gregor5c407d92008-10-23 00:40:37 +0000987 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +0000988 //
Douglas Gregor5c407d92008-10-23 00:40:37 +0000989 // An rvalue of type "pointer to cv D," where D is a class type,
990 // can be converted to an rvalue of type "pointer to cv B," where
991 // B is a base class (clause 10) of D. If B is an inaccessible
992 // (clause 11) or ambiguous (10.2) base class of D, a program that
993 // necessitates this conversion is ill-formed. The result of the
994 // conversion is a pointer to the base class sub-object of the
995 // derived class object. The null pointer value is converted to
996 // the null pointer value of the destination type.
997 //
Douglas Gregor39c16d42008-10-24 04:54:22 +0000998 // Note that we do not check for ambiguity or inaccessibility
999 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001000 if (getLangOptions().CPlusPlus &&
1001 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001002 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001003 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001004 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001005 ToType, Context);
1006 return true;
1007 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001008
Douglas Gregora119f102008-12-19 19:13:09 +00001009 return false;
1010}
1011
1012/// isObjCPointerConversion - Determines whether this is an
1013/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1014/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001015bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001016 QualType& ConvertedType,
1017 bool &IncompatibleObjC) {
1018 if (!getLangOptions().ObjC1)
1019 return false;
1020
Steve Naroff7cae42b2009-07-10 23:34:53 +00001021 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001022 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001023 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001024 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001025
Steve Naroff7cae42b2009-07-10 23:34:53 +00001026 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001027 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001028 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001029 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001030 ConvertedType = ToType;
1031 return true;
1032 }
1033 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001034 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001035 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001036 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001037 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001038 ConvertedType = ToType;
1039 return true;
1040 }
1041 // Objective C++: We're able to convert from a pointer to an
1042 // interface to a pointer to a different interface.
1043 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1044 ConvertedType = ToType;
1045 return true;
1046 }
1047
1048 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1049 // Okay: this is some kind of implicit downcast of Objective-C
1050 // interfaces, which is permitted. However, we're going to
1051 // complain about it.
1052 IncompatibleObjC = true;
1053 ConvertedType = FromType;
1054 return true;
1055 }
Mike Stump11289f42009-09-09 15:08:12 +00001056 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001057 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001058 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001059 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001060 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001061 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001062 ToPointeeType = ToBlockPtr->getPointeeType();
1063 else
Douglas Gregora119f102008-12-19 19:13:09 +00001064 return false;
1065
Douglas Gregor033f56d2008-12-23 00:53:59 +00001066 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001067 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001068 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001069 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001070 FromPointeeType = FromBlockPtr->getPointeeType();
1071 else
Douglas Gregora119f102008-12-19 19:13:09 +00001072 return false;
1073
Douglas Gregora119f102008-12-19 19:13:09 +00001074 // If we have pointers to pointers, recursively check whether this
1075 // is an Objective-C conversion.
1076 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1077 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1078 IncompatibleObjC)) {
1079 // We always complain about this conversion.
1080 IncompatibleObjC = true;
1081 ConvertedType = ToType;
1082 return true;
1083 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001084 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001085 // differences in the argument and result types are in Objective-C
1086 // pointer conversions. If so, we permit the conversion (but
1087 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001088 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001089 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001090 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001091 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001092 if (FromFunctionType && ToFunctionType) {
1093 // If the function types are exactly the same, this isn't an
1094 // Objective-C pointer conversion.
1095 if (Context.getCanonicalType(FromPointeeType)
1096 == Context.getCanonicalType(ToPointeeType))
1097 return false;
1098
1099 // Perform the quick checks that will tell us whether these
1100 // function types are obviously different.
1101 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1102 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1103 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1104 return false;
1105
1106 bool HasObjCConversion = false;
1107 if (Context.getCanonicalType(FromFunctionType->getResultType())
1108 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1109 // Okay, the types match exactly. Nothing to do.
1110 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1111 ToFunctionType->getResultType(),
1112 ConvertedType, IncompatibleObjC)) {
1113 // Okay, we have an Objective-C pointer conversion.
1114 HasObjCConversion = true;
1115 } else {
1116 // Function types are too different. Abort.
1117 return false;
1118 }
Mike Stump11289f42009-09-09 15:08:12 +00001119
Douglas Gregora119f102008-12-19 19:13:09 +00001120 // Check argument types.
1121 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1122 ArgIdx != NumArgs; ++ArgIdx) {
1123 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1124 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1125 if (Context.getCanonicalType(FromArgType)
1126 == Context.getCanonicalType(ToArgType)) {
1127 // Okay, the types match exactly. Nothing to do.
1128 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1129 ConvertedType, IncompatibleObjC)) {
1130 // Okay, we have an Objective-C pointer conversion.
1131 HasObjCConversion = true;
1132 } else {
1133 // Argument types are too different. Abort.
1134 return false;
1135 }
1136 }
1137
1138 if (HasObjCConversion) {
1139 // We had an Objective-C conversion. Allow this pointer
1140 // conversion, but complain about it.
1141 ConvertedType = ToType;
1142 IncompatibleObjC = true;
1143 return true;
1144 }
1145 }
1146
Sebastian Redl72b597d2009-01-25 19:43:20 +00001147 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001148}
1149
Douglas Gregor39c16d42008-10-24 04:54:22 +00001150/// CheckPointerConversion - Check the pointer conversion from the
1151/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001152/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001153/// conversions for which IsPointerConversion has already returned
1154/// true. It returns true and produces a diagnostic if there was an
1155/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001156bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
1157 CastExpr::CastKind &Kind) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001158 QualType FromType = From->getType();
1159
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001160 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1161 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001162 QualType FromPointeeType = FromPtrType->getPointeeType(),
1163 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001164
Douglas Gregor39c16d42008-10-24 04:54:22 +00001165 if (FromPointeeType->isRecordType() &&
1166 ToPointeeType->isRecordType()) {
1167 // We must have a derived-to-base conversion. Check an
1168 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001169 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1170 From->getExprLoc(),
1171 From->getSourceRange()))
1172 return true;
1173
1174 // The conversion was successful.
1175 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001176 }
1177 }
Mike Stump11289f42009-09-09 15:08:12 +00001178 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001179 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001180 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001181 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001182 // Objective-C++ conversions are always okay.
1183 // FIXME: We should have a different class of conversions for the
1184 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001185 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001186 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001187
Steve Naroff7cae42b2009-07-10 23:34:53 +00001188 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001189 return false;
1190}
1191
Sebastian Redl72b597d2009-01-25 19:43:20 +00001192/// IsMemberPointerConversion - Determines whether the conversion of the
1193/// expression From, which has the (possibly adjusted) type FromType, can be
1194/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1195/// If so, returns true and places the converted type (that might differ from
1196/// ToType in its cv-qualifiers at some level) into ConvertedType.
1197bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001198 QualType ToType,
1199 bool InOverloadResolution,
1200 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001201 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001202 if (!ToTypePtr)
1203 return false;
1204
1205 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001206 if (From->isNullPointerConstant(Context,
1207 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1208 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001209 ConvertedType = ToType;
1210 return true;
1211 }
1212
1213 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001214 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001215 if (!FromTypePtr)
1216 return false;
1217
1218 // A pointer to member of B can be converted to a pointer to member of D,
1219 // where D is derived from B (C++ 4.11p2).
1220 QualType FromClass(FromTypePtr->getClass(), 0);
1221 QualType ToClass(ToTypePtr->getClass(), 0);
1222 // FIXME: What happens when these are dependent? Is this function even called?
1223
1224 if (IsDerivedFrom(ToClass, FromClass)) {
1225 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1226 ToClass.getTypePtr());
1227 return true;
1228 }
1229
1230 return false;
1231}
1232
1233/// CheckMemberPointerConversion - Check the member pointer conversion from the
1234/// expression From to the type ToType. This routine checks for ambiguous or
1235/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1236/// for which IsMemberPointerConversion has already returned true. It returns
1237/// true and produces a diagnostic if there was an error, or returns false
1238/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001239bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Anders Carlssond7923c62009-08-22 23:33:40 +00001240 CastExpr::CastKind &Kind) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001241 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001242 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001243 if (!FromPtrType) {
1244 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001245 assert(From->isNullPointerConstant(Context,
1246 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001247 "Expr must be null pointer constant!");
1248 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001249 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001250 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001251
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001252 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001253 assert(ToPtrType && "No member pointer cast has a target type "
1254 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001255
Sebastian Redled8f2002009-01-28 18:33:18 +00001256 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1257 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001258
Sebastian Redled8f2002009-01-28 18:33:18 +00001259 // FIXME: What about dependent types?
1260 assert(FromClass->isRecordType() && "Pointer into non-class.");
1261 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001262
Douglas Gregor36d1b142009-10-06 17:59:45 +00001263 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1264 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001265 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1266 assert(DerivationOkay &&
1267 "Should not have been called if derivation isn't OK.");
1268 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001269
Sebastian Redled8f2002009-01-28 18:33:18 +00001270 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1271 getUnqualifiedType())) {
1272 // Derivation is ambiguous. Redo the check to find the exact paths.
1273 Paths.clear();
1274 Paths.setRecordingPaths(true);
1275 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1276 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1277 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001278
Sebastian Redled8f2002009-01-28 18:33:18 +00001279 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1280 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1281 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1282 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001283 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001284
Douglas Gregor89ee6822009-02-28 01:32:25 +00001285 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001286 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1287 << FromClass << ToClass << QualType(VBase, 0)
1288 << From->getSourceRange();
1289 return true;
1290 }
1291
Anders Carlssond7923c62009-08-22 23:33:40 +00001292 // Must be a base to derived member conversion.
1293 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001294 return false;
1295}
1296
Douglas Gregor9a657932008-10-21 23:43:52 +00001297/// IsQualificationConversion - Determines whether the conversion from
1298/// an rvalue of type FromType to ToType is a qualification conversion
1299/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001300bool
1301Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001302 FromType = Context.getCanonicalType(FromType);
1303 ToType = Context.getCanonicalType(ToType);
1304
1305 // If FromType and ToType are the same type, this is not a
1306 // qualification conversion.
1307 if (FromType == ToType)
1308 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001309
Douglas Gregor9a657932008-10-21 23:43:52 +00001310 // (C++ 4.4p4):
1311 // A conversion can add cv-qualifiers at levels other than the first
1312 // in multi-level pointers, subject to the following rules: [...]
1313 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001314 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001315 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001316 // Within each iteration of the loop, we check the qualifiers to
1317 // determine if this still looks like a qualification
1318 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001319 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001320 // until there are no more pointers or pointers-to-members left to
1321 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001322 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001323
1324 // -- for every j > 0, if const is in cv 1,j then const is in cv
1325 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001326 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001327 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001328
Douglas Gregor9a657932008-10-21 23:43:52 +00001329 // -- if the cv 1,j and cv 2,j are different, then const is in
1330 // every cv for 0 < k < j.
1331 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001332 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001333 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001334
Douglas Gregor9a657932008-10-21 23:43:52 +00001335 // Keep track of whether all prior cv-qualifiers in the "to" type
1336 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001337 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001338 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001339 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001340
1341 // We are left with FromType and ToType being the pointee types
1342 // after unwrapping the original FromType and ToType the same number
1343 // of types. If we unwrapped any pointers, and if FromType and
1344 // ToType have the same unqualified type (since we checked
1345 // qualifiers above), then this is a qualification conversion.
1346 return UnwrappedAnyPointer &&
1347 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1348}
1349
Douglas Gregor05155d82009-08-21 23:19:43 +00001350/// \brief Given a function template or function, extract the function template
1351/// declaration (if any) and the underlying function declaration.
1352template<typename T>
1353static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1354 FunctionTemplateDecl *&FunctionTemplate) {
1355 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1356 if (FunctionTemplate)
1357 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1358 else
1359 Function = cast<T>(Orig);
1360}
1361
Douglas Gregor576e98c2009-01-30 23:27:23 +00001362/// Determines whether there is a user-defined conversion sequence
1363/// (C++ [over.ics.user]) that converts expression From to the type
1364/// ToType. If such a conversion exists, User will contain the
1365/// user-defined conversion sequence that performs such a conversion
1366/// and this routine will return true. Otherwise, this routine returns
1367/// false and User is unspecified.
1368///
1369/// \param AllowConversionFunctions true if the conversion should
1370/// consider conversion functions at all. If false, only constructors
1371/// will be considered.
1372///
1373/// \param AllowExplicit true if the conversion should consider C++0x
1374/// "explicit" conversion functions as well as non-explicit conversion
1375/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001376///
1377/// \param ForceRValue true if the expression should be treated as an rvalue
1378/// for overload resolution.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001379/// \param UserCast true if looking for user defined conversion for a static
1380/// cast.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001381Sema::OverloadingResult Sema::IsUserDefinedConversion(
1382 Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001383 UserDefinedConversionSequence& User,
Fariborz Jahanian19c73282009-09-15 00:10:11 +00001384 OverloadCandidateSet& CandidateSet,
Douglas Gregor576e98c2009-01-30 23:27:23 +00001385 bool AllowConversionFunctions,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001386 bool AllowExplicit, bool ForceRValue,
1387 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001388 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001389 if (CXXRecordDecl *ToRecordDecl
Douglas Gregor89ee6822009-02-28 01:32:25 +00001390 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1391 // C++ [over.match.ctor]p1:
1392 // When objects of class type are direct-initialized (8.5), or
1393 // copy-initialized from an expression of the same or a
1394 // derived class type (8.5), overload resolution selects the
1395 // constructor. [...] For copy-initialization, the candidate
1396 // functions are all the converting constructors (12.3.1) of
1397 // that class. The argument list is the expression-list within
1398 // the parentheses of the initializer.
Mike Stump11289f42009-09-09 15:08:12 +00001399 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001400 = Context.DeclarationNames.getCXXConstructorName(
1401 Context.getCanonicalType(ToType).getUnqualifiedType());
1402 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001403 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001404 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001405 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001406 // Find the constructor (which may be a template).
1407 CXXConstructorDecl *Constructor = 0;
1408 FunctionTemplateDecl *ConstructorTmpl
1409 = dyn_cast<FunctionTemplateDecl>(*Con);
1410 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001411 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001412 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1413 else
1414 Constructor = cast<CXXConstructorDecl>(*Con);
Mike Stump11289f42009-09-09 15:08:12 +00001415
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001416 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001417 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001418 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001419 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001420 1, CandidateSet,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001421 /*SuppressUserConversions=*/!UserCast,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001422 ForceRValue);
1423 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001424 // Allow one user-defined conversion when user specifies a
1425 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001426 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001427 /*SuppressUserConversions=*/!UserCast,
1428 ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001429 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001430 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001431 }
1432 }
1433
Douglas Gregor576e98c2009-01-30 23:27:23 +00001434 if (!AllowConversionFunctions) {
1435 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001436 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1437 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001438 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001439 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001440 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001441 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001442 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001443 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1444 // Add all of the conversion functions as candidates.
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001445 OverloadedFunctionDecl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001446 = FromRecordDecl->getVisibleConversionFunctions();
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001447 for (OverloadedFunctionDecl::function_iterator Func
1448 = Conversions->function_begin();
1449 Func != Conversions->function_end(); ++Func) {
1450 CXXConversionDecl *Conv;
1451 FunctionTemplateDecl *ConvTemplate;
1452 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1453 if (ConvTemplate)
1454 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1455 else
1456 Conv = dyn_cast<CXXConversionDecl>(*Func);
1457
1458 if (AllowExplicit || !Conv->isExplicit()) {
1459 if (ConvTemplate)
1460 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1461 CandidateSet);
1462 else
1463 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1464 }
1465 }
1466 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001467 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001468
1469 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001470 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001471 case OR_Success:
1472 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001473 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001474 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1475 // C++ [over.ics.user]p1:
1476 // If the user-defined conversion is specified by a
1477 // constructor (12.3.1), the initial standard conversion
1478 // sequence converts the source type to the type required by
1479 // the argument of the constructor.
1480 //
1481 // FIXME: What about ellipsis conversions?
1482 QualType ThisType = Constructor->getThisType(Context);
1483 User.Before = Best->Conversions[0].Standard;
1484 User.ConversionFunction = Constructor;
1485 User.After.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00001486 User.After.FromTypePtr
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001487 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001488 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001489 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001490 } else if (CXXConversionDecl *Conversion
1491 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1492 // C++ [over.ics.user]p1:
1493 //
1494 // [...] If the user-defined conversion is specified by a
1495 // conversion function (12.3.2), the initial standard
1496 // conversion sequence converts the source type to the
1497 // implicit object parameter of the conversion function.
1498 User.Before = Best->Conversions[0].Standard;
1499 User.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00001500
1501 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001502 // The second standard conversion sequence converts the
1503 // result of the user-defined conversion to the target type
1504 // for the sequence. Since an implicit conversion sequence
1505 // is an initialization, the special rules for
1506 // initialization by user-defined conversion apply when
1507 // selecting the best user-defined conversion for a
1508 // user-defined conversion sequence (see 13.3.3 and
1509 // 13.3.3.1).
1510 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001511 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001512 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001513 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001514 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001515 }
Mike Stump11289f42009-09-09 15:08:12 +00001516
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001517 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001518 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001519 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001520 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001521 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001522
1523 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001524 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001525 }
1526
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001527 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001528}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001529
1530bool
1531Sema::DiagnoseAmbiguousUserDefinedConversion(Expr *From, QualType ToType) {
1532 ImplicitConversionSequence ICS;
1533 OverloadCandidateSet CandidateSet;
1534 OverloadingResult OvResult =
1535 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1536 CandidateSet, true, false, false);
1537 if (OvResult != OR_Ambiguous)
1538 return false;
1539 Diag(From->getSourceRange().getBegin(),
1540 diag::err_typecheck_ambiguous_condition)
1541 << From->getType() << ToType << From->getSourceRange();
1542 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1543 return true;
1544}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001545
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001546/// CompareImplicitConversionSequences - Compare two implicit
1547/// conversion sequences to determine whether one is better than the
1548/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001549ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001550Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1551 const ImplicitConversionSequence& ICS2)
1552{
1553 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1554 // conversion sequences (as defined in 13.3.3.1)
1555 // -- a standard conversion sequence (13.3.3.1.1) is a better
1556 // conversion sequence than a user-defined conversion sequence or
1557 // an ellipsis conversion sequence, and
1558 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1559 // conversion sequence than an ellipsis conversion sequence
1560 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001561 //
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001562 if (ICS1.ConversionKind < ICS2.ConversionKind)
1563 return ImplicitConversionSequence::Better;
1564 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1565 return ImplicitConversionSequence::Worse;
1566
1567 // Two implicit conversion sequences of the same form are
1568 // indistinguishable conversion sequences unless one of the
1569 // following rules apply: (C++ 13.3.3.2p3):
1570 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1571 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump11289f42009-09-09 15:08:12 +00001572 else if (ICS1.ConversionKind ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001573 ImplicitConversionSequence::UserDefinedConversion) {
1574 // User-defined conversion sequence U1 is a better conversion
1575 // sequence than another user-defined conversion sequence U2 if
1576 // they contain the same user-defined conversion function or
1577 // constructor and if the second standard conversion sequence of
1578 // U1 is better than the second standard conversion sequence of
1579 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001580 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001581 ICS2.UserDefined.ConversionFunction)
1582 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1583 ICS2.UserDefined.After);
1584 }
1585
1586 return ImplicitConversionSequence::Indistinguishable;
1587}
1588
1589/// CompareStandardConversionSequences - Compare two standard
1590/// conversion sequences to determine whether one is better than the
1591/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001592ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001593Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1594 const StandardConversionSequence& SCS2)
1595{
1596 // Standard conversion sequence S1 is a better conversion sequence
1597 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1598
1599 // -- S1 is a proper subsequence of S2 (comparing the conversion
1600 // sequences in the canonical form defined by 13.3.3.1.1,
1601 // excluding any Lvalue Transformation; the identity conversion
1602 // sequence is considered to be a subsequence of any
1603 // non-identity conversion sequence) or, if not that,
1604 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1605 // Neither is a proper subsequence of the other. Do nothing.
1606 ;
1607 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1608 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001609 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001610 SCS1.Third == ICK_Identity))
1611 // SCS1 is a proper subsequence of SCS2.
1612 return ImplicitConversionSequence::Better;
1613 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1614 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001615 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001616 SCS2.Third == ICK_Identity))
1617 // SCS2 is a proper subsequence of SCS1.
1618 return ImplicitConversionSequence::Worse;
1619
1620 // -- the rank of S1 is better than the rank of S2 (by the rules
1621 // defined below), or, if not that,
1622 ImplicitConversionRank Rank1 = SCS1.getRank();
1623 ImplicitConversionRank Rank2 = SCS2.getRank();
1624 if (Rank1 < Rank2)
1625 return ImplicitConversionSequence::Better;
1626 else if (Rank2 < Rank1)
1627 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001628
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001629 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1630 // are indistinguishable unless one of the following rules
1631 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001632
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001633 // A conversion that is not a conversion of a pointer, or
1634 // pointer to member, to bool is better than another conversion
1635 // that is such a conversion.
1636 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1637 return SCS2.isPointerConversionToBool()
1638 ? ImplicitConversionSequence::Better
1639 : ImplicitConversionSequence::Worse;
1640
Douglas Gregor5c407d92008-10-23 00:40:37 +00001641 // C++ [over.ics.rank]p4b2:
1642 //
1643 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001644 // conversion of B* to A* is better than conversion of B* to
1645 // void*, and conversion of A* to void* is better than conversion
1646 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001647 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001648 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001649 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001650 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001651 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1652 // Exactly one of the conversion sequences is a conversion to
1653 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001654 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1655 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001656 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1657 // Neither conversion sequence converts to a void pointer; compare
1658 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001659 if (ImplicitConversionSequence::CompareKind DerivedCK
1660 = CompareDerivedToBaseConversions(SCS1, SCS2))
1661 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001662 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1663 // Both conversion sequences are conversions to void
1664 // pointers. Compare the source types to determine if there's an
1665 // inheritance relationship in their sources.
1666 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1667 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1668
1669 // Adjust the types we're converting from via the array-to-pointer
1670 // conversion, if we need to.
1671 if (SCS1.First == ICK_Array_To_Pointer)
1672 FromType1 = Context.getArrayDecayedType(FromType1);
1673 if (SCS2.First == ICK_Array_To_Pointer)
1674 FromType2 = Context.getArrayDecayedType(FromType2);
1675
Mike Stump11289f42009-09-09 15:08:12 +00001676 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001677 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001678 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001679 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001680
1681 if (IsDerivedFrom(FromPointee2, FromPointee1))
1682 return ImplicitConversionSequence::Better;
1683 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1684 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001685
1686 // Objective-C++: If one interface is more specific than the
1687 // other, it is the better one.
John McCall9dd450b2009-09-21 23:43:11 +00001688 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1689 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001690 if (FromIface1 && FromIface1) {
1691 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1692 return ImplicitConversionSequence::Better;
1693 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1694 return ImplicitConversionSequence::Worse;
1695 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001696 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001697
1698 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1699 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001700 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001701 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001702 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001703
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001704 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001705 // C++0x [over.ics.rank]p3b4:
1706 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1707 // implicit object parameter of a non-static member function declared
1708 // without a ref-qualifier, and S1 binds an rvalue reference to an
1709 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001710 // FIXME: We don't know if we're dealing with the implicit object parameter,
1711 // or if the member function in this case has a ref qualifier.
1712 // (Of course, we don't have ref qualifiers yet.)
1713 if (SCS1.RRefBinding != SCS2.RRefBinding)
1714 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1715 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001716
1717 // C++ [over.ics.rank]p3b4:
1718 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1719 // which the references refer are the same type except for
1720 // top-level cv-qualifiers, and the type to which the reference
1721 // initialized by S2 refers is more cv-qualified than the type
1722 // to which the reference initialized by S1 refers.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001723 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1724 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001725 T1 = Context.getCanonicalType(T1);
1726 T2 = Context.getCanonicalType(T2);
1727 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1728 if (T2.isMoreQualifiedThan(T1))
1729 return ImplicitConversionSequence::Better;
1730 else if (T1.isMoreQualifiedThan(T2))
1731 return ImplicitConversionSequence::Worse;
1732 }
1733 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001734
1735 return ImplicitConversionSequence::Indistinguishable;
1736}
1737
1738/// CompareQualificationConversions - Compares two standard conversion
1739/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001740/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1741ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001742Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001743 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001744 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001745 // -- S1 and S2 differ only in their qualification conversion and
1746 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1747 // cv-qualification signature of type T1 is a proper subset of
1748 // the cv-qualification signature of type T2, and S1 is not the
1749 // deprecated string literal array-to-pointer conversion (4.2).
1750 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1751 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1752 return ImplicitConversionSequence::Indistinguishable;
1753
1754 // FIXME: the example in the standard doesn't use a qualification
1755 // conversion (!)
1756 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1757 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1758 T1 = Context.getCanonicalType(T1);
1759 T2 = Context.getCanonicalType(T2);
1760
1761 // If the types are the same, we won't learn anything by unwrapped
1762 // them.
1763 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1764 return ImplicitConversionSequence::Indistinguishable;
1765
Mike Stump11289f42009-09-09 15:08:12 +00001766 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001767 = ImplicitConversionSequence::Indistinguishable;
1768 while (UnwrapSimilarPointerTypes(T1, T2)) {
1769 // Within each iteration of the loop, we check the qualifiers to
1770 // determine if this still looks like a qualification
1771 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001772 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001773 // until there are no more pointers or pointers-to-members left
1774 // to unwrap. This essentially mimics what
1775 // IsQualificationConversion does, but here we're checking for a
1776 // strict subset of qualifiers.
1777 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1778 // The qualifiers are the same, so this doesn't tell us anything
1779 // about how the sequences rank.
1780 ;
1781 else if (T2.isMoreQualifiedThan(T1)) {
1782 // T1 has fewer qualifiers, so it could be the better sequence.
1783 if (Result == ImplicitConversionSequence::Worse)
1784 // Neither has qualifiers that are a subset of the other's
1785 // qualifiers.
1786 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001787
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001788 Result = ImplicitConversionSequence::Better;
1789 } else if (T1.isMoreQualifiedThan(T2)) {
1790 // T2 has fewer qualifiers, so it could be the better sequence.
1791 if (Result == ImplicitConversionSequence::Better)
1792 // Neither has qualifiers that are a subset of the other's
1793 // qualifiers.
1794 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001795
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001796 Result = ImplicitConversionSequence::Worse;
1797 } else {
1798 // Qualifiers are disjoint.
1799 return ImplicitConversionSequence::Indistinguishable;
1800 }
1801
1802 // If the types after this point are equivalent, we're done.
1803 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1804 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001805 }
1806
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001807 // Check that the winning standard conversion sequence isn't using
1808 // the deprecated string literal array to pointer conversion.
1809 switch (Result) {
1810 case ImplicitConversionSequence::Better:
1811 if (SCS1.Deprecated)
1812 Result = ImplicitConversionSequence::Indistinguishable;
1813 break;
1814
1815 case ImplicitConversionSequence::Indistinguishable:
1816 break;
1817
1818 case ImplicitConversionSequence::Worse:
1819 if (SCS2.Deprecated)
1820 Result = ImplicitConversionSequence::Indistinguishable;
1821 break;
1822 }
1823
1824 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001825}
1826
Douglas Gregor5c407d92008-10-23 00:40:37 +00001827/// CompareDerivedToBaseConversions - Compares two standard conversion
1828/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001829/// various kinds of derived-to-base conversions (C++
1830/// [over.ics.rank]p4b3). As part of these checks, we also look at
1831/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001832ImplicitConversionSequence::CompareKind
1833Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1834 const StandardConversionSequence& SCS2) {
1835 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1836 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1837 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1838 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1839
1840 // Adjust the types we're converting from via the array-to-pointer
1841 // conversion, if we need to.
1842 if (SCS1.First == ICK_Array_To_Pointer)
1843 FromType1 = Context.getArrayDecayedType(FromType1);
1844 if (SCS2.First == ICK_Array_To_Pointer)
1845 FromType2 = Context.getArrayDecayedType(FromType2);
1846
1847 // Canonicalize all of the types.
1848 FromType1 = Context.getCanonicalType(FromType1);
1849 ToType1 = Context.getCanonicalType(ToType1);
1850 FromType2 = Context.getCanonicalType(FromType2);
1851 ToType2 = Context.getCanonicalType(ToType2);
1852
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001853 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001854 //
1855 // If class B is derived directly or indirectly from class A and
1856 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001857 //
1858 // For Objective-C, we let A, B, and C also be Objective-C
1859 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001860
1861 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00001862 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00001863 SCS2.Second == ICK_Pointer_Conversion &&
1864 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1865 FromType1->isPointerType() && FromType2->isPointerType() &&
1866 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001867 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001868 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001869 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001870 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001871 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001872 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001873 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001874 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001875
John McCall9dd450b2009-09-21 23:43:11 +00001876 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1877 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1878 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1879 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001880
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001881 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00001882 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1883 if (IsDerivedFrom(ToPointee1, ToPointee2))
1884 return ImplicitConversionSequence::Better;
1885 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1886 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001887
1888 if (ToIface1 && ToIface2) {
1889 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1890 return ImplicitConversionSequence::Better;
1891 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1892 return ImplicitConversionSequence::Worse;
1893 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001894 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001895
1896 // -- conversion of B* to A* is better than conversion of C* to A*,
1897 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1898 if (IsDerivedFrom(FromPointee2, FromPointee1))
1899 return ImplicitConversionSequence::Better;
1900 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1901 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00001902
Douglas Gregor237f96c2008-11-26 23:31:11 +00001903 if (FromIface1 && FromIface2) {
1904 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1905 return ImplicitConversionSequence::Better;
1906 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1907 return ImplicitConversionSequence::Worse;
1908 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001909 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001910 }
1911
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001912 // Compare based on reference bindings.
1913 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1914 SCS1.Second == ICK_Derived_To_Base) {
1915 // -- binding of an expression of type C to a reference of type
1916 // B& is better than binding an expression of type C to a
1917 // reference of type A&,
1918 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1919 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1920 if (IsDerivedFrom(ToType1, ToType2))
1921 return ImplicitConversionSequence::Better;
1922 else if (IsDerivedFrom(ToType2, ToType1))
1923 return ImplicitConversionSequence::Worse;
1924 }
1925
Douglas Gregor2fe98832008-11-03 19:09:14 +00001926 // -- binding of an expression of type B to a reference of type
1927 // A& is better than binding an expression of type C to a
1928 // reference of type A&,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001929 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1930 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1931 if (IsDerivedFrom(FromType2, FromType1))
1932 return ImplicitConversionSequence::Better;
1933 else if (IsDerivedFrom(FromType1, FromType2))
1934 return ImplicitConversionSequence::Worse;
1935 }
1936 }
1937
1938
1939 // FIXME: conversion of A::* to B::* is better than conversion of
1940 // A::* to C::*,
1941
1942 // FIXME: conversion of B::* to C::* is better than conversion of
1943 // A::* to C::*, and
1944
Douglas Gregor2fe98832008-11-03 19:09:14 +00001945 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1946 SCS1.Second == ICK_Derived_To_Base) {
1947 // -- conversion of C to B is better than conversion of C to A,
1948 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1949 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1950 if (IsDerivedFrom(ToType1, ToType2))
1951 return ImplicitConversionSequence::Better;
1952 else if (IsDerivedFrom(ToType2, ToType1))
1953 return ImplicitConversionSequence::Worse;
1954 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001955
Douglas Gregor2fe98832008-11-03 19:09:14 +00001956 // -- conversion of B to A is better than conversion of C to A.
1957 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1958 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1959 if (IsDerivedFrom(FromType2, FromType1))
1960 return ImplicitConversionSequence::Better;
1961 else if (IsDerivedFrom(FromType1, FromType2))
1962 return ImplicitConversionSequence::Worse;
1963 }
1964 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001965
Douglas Gregor5c407d92008-10-23 00:40:37 +00001966 return ImplicitConversionSequence::Indistinguishable;
1967}
1968
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001969/// TryCopyInitialization - Try to copy-initialize a value of type
1970/// ToType from the expression From. Return the implicit conversion
1971/// sequence required to pass this argument, which may be a bad
1972/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00001973/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00001974/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1975/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00001976ImplicitConversionSequence
1977Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00001978 bool SuppressUserConversions, bool ForceRValue,
1979 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001980 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001981 ImplicitConversionSequence ICS;
Mike Stump11289f42009-09-09 15:08:12 +00001982 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00001983 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00001984 SuppressUserConversions,
1985 /*AllowExplicit=*/false,
1986 ForceRValue,
1987 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001988 return ICS;
1989 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001990 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00001991 SuppressUserConversions,
1992 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001993 ForceRValue,
1994 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001995 }
1996}
1997
Sebastian Redl42e92c42009-04-12 17:16:29 +00001998/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1999/// the expression @p From. Returns true (and emits a diagnostic) if there was
2000/// an error, returns false if the initialization succeeded. Elidable should
2001/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2002/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002003bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002004 const char* Flavor, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002005 if (!getLangOptions().CPlusPlus) {
2006 // In C, argument passing is the same as performing an assignment.
2007 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002008
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002009 AssignConvertType ConvTy =
2010 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002011 if (ConvTy != Compatible &&
2012 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2013 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002014
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002015 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2016 FromType, From, Flavor);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002017 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002018
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002019 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002020 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002021 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002022 /*SuppressUserConversions=*/false,
2023 /*AllowExplicit=*/false,
2024 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002025
Sebastian Redl42e92c42009-04-12 17:16:29 +00002026 if (!PerformImplicitConversion(From, ToType, Flavor,
2027 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002028 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002029 if (!DiagnoseAmbiguousUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002030 return Diag(From->getSourceRange().getBegin(),
2031 diag::err_typecheck_convert_incompatible)
2032 << ToType << From->getType() << Flavor << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002033 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002034}
2035
Douglas Gregor436424c2008-11-18 23:14:02 +00002036/// TryObjectArgumentInitialization - Try to initialize the object
2037/// parameter of the given member function (@c Method) from the
2038/// expression @p From.
2039ImplicitConversionSequence
2040Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
2041 QualType ClassType = Context.getTypeDeclType(Method->getParent());
John McCall8ccfcb52009-09-24 19:53:00 +00002042 QualType ImplicitParamType
2043 = Context.getCVRQualifiedType(ClassType, Method->getTypeQualifiers());
Douglas Gregor436424c2008-11-18 23:14:02 +00002044
2045 // Set up the conversion sequence as a "bad" conversion, to allow us
2046 // to exit early.
2047 ImplicitConversionSequence ICS;
2048 ICS.Standard.setAsIdentityConversion();
2049 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2050
2051 // We need to have an object of class type.
2052 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002053 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002054 FromType = PT->getPointeeType();
2055
2056 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002057
2058 // The implicit object parmeter is has the type "reference to cv X",
2059 // where X is the class of which the function is a member
2060 // (C++ [over.match.funcs]p4). However, when finding an implicit
2061 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002062 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002063 // (C++ [over.match.funcs]p5). We perform a simplified version of
2064 // reference binding here, that allows class rvalues to bind to
2065 // non-constant references.
2066
2067 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2068 // with the implicit object parameter (C++ [over.match.funcs]p5).
2069 QualType FromTypeCanon = Context.getCanonicalType(FromType);
2070 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2071 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2072 return ICS;
2073
2074 // Check that we have either the same type or a derived type. It
2075 // affects the conversion rank.
2076 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2077 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2078 ICS.Standard.Second = ICK_Identity;
2079 else if (IsDerivedFrom(FromType, ClassType))
2080 ICS.Standard.Second = ICK_Derived_To_Base;
2081 else
2082 return ICS;
2083
2084 // Success. Mark this as a reference binding.
2085 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2086 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2087 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2088 ICS.Standard.ReferenceBinding = true;
2089 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002090 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002091 return ICS;
2092}
2093
2094/// PerformObjectArgumentInitialization - Perform initialization of
2095/// the implicit object parameter for the given Method with the given
2096/// expression.
2097bool
2098Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002099 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002100 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002101 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002102
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002103 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002104 FromRecordType = PT->getPointeeType();
2105 DestType = Method->getThisType(Context);
2106 } else {
2107 FromRecordType = From->getType();
2108 DestType = ImplicitParamRecordType;
2109 }
2110
Mike Stump11289f42009-09-09 15:08:12 +00002111 ImplicitConversionSequence ICS
Douglas Gregor436424c2008-11-18 23:14:02 +00002112 = TryObjectArgumentInitialization(From, Method);
2113 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2114 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002115 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002116 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002117
Douglas Gregor436424c2008-11-18 23:14:02 +00002118 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002119 CheckDerivedToBaseConversion(FromRecordType,
2120 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002121 From->getSourceRange().getBegin(),
2122 From->getSourceRange()))
2123 return true;
2124
Mike Stump11289f42009-09-09 15:08:12 +00002125 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002126 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002127 return false;
2128}
2129
Douglas Gregor5fb53972009-01-14 15:45:31 +00002130/// TryContextuallyConvertToBool - Attempt to contextually convert the
2131/// expression From to bool (C++0x [conv]p3).
2132ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002133 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002134 // FIXME: Are these flags correct?
2135 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002136 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002137 /*ForceRValue=*/false,
2138 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002139}
2140
2141/// PerformContextuallyConvertToBool - Perform a contextual conversion
2142/// of the expression From to bool (C++0x [conv]p3).
2143bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2144 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2145 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2146 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002147
2148 if (!DiagnoseAmbiguousUserDefinedConversion(From, Context.BoolTy))
2149 return Diag(From->getSourceRange().getBegin(),
2150 diag::err_typecheck_bool_condition)
2151 << From->getType() << From->getSourceRange();
2152 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002153}
2154
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002155/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002156/// candidate functions, using the given function call arguments. If
2157/// @p SuppressUserConversions, then don't allow user-defined
2158/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002159/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2160/// hacky way to implement the overloading rules for elidable copy
2161/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002162///
2163/// \para PartialOverloading true if we are performing "partial" overloading
2164/// based on an incomplete set of function arguments. This feature is used by
2165/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002166void
2167Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002168 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002169 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002170 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002171 bool ForceRValue,
2172 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002173 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002174 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002175 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002176 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002177 "Use AddConversionCandidate for conversion functions");
Mike Stump11289f42009-09-09 15:08:12 +00002178 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002179 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002180
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002181 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002182 if (!isa<CXXConstructorDecl>(Method)) {
2183 // If we get here, it's because we're calling a member function
2184 // that is named without a member access expression (e.g.,
2185 // "this->f") that was either written explicitly or created
2186 // implicitly. This can happen with a qualified call to a member
2187 // function, e.g., X::f(). We use a NULL object as the implied
2188 // object argument (C++ [over.call.func]p3).
Mike Stump11289f42009-09-09 15:08:12 +00002189 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002190 SuppressUserConversions, ForceRValue);
2191 return;
2192 }
2193 // We treat a constructor like a non-member function, since its object
2194 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002195 }
2196
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002197 if (!CandidateSet.isNewCandidate(Function))
2198 return;
2199
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002200 // Add this candidate
2201 CandidateSet.push_back(OverloadCandidate());
2202 OverloadCandidate& Candidate = CandidateSet.back();
2203 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002204 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002205 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002206 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002207
2208 unsigned NumArgsInProto = Proto->getNumArgs();
2209
2210 // (C++ 13.3.2p2): A candidate function having fewer than m
2211 // parameters is viable only if it has an ellipsis in its parameter
2212 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002213 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2214 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002215 Candidate.Viable = false;
2216 return;
2217 }
2218
2219 // (C++ 13.3.2p2): A candidate function having more than m parameters
2220 // is viable only if the (m+1)st parameter has a default argument
2221 // (8.3.6). For the purposes of overload resolution, the
2222 // parameter list is truncated on the right, so that there are
2223 // exactly m parameters.
2224 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002225 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002226 // Not enough arguments.
2227 Candidate.Viable = false;
2228 return;
2229 }
2230
2231 // Determine the implicit conversion sequences for each of the
2232 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002233 Candidate.Conversions.resize(NumArgs);
2234 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2235 if (ArgIdx < NumArgsInProto) {
2236 // (C++ 13.3.2p3): for F to be a viable function, there shall
2237 // exist for each argument an implicit conversion sequence
2238 // (13.3.3.1) that converts that argument to the corresponding
2239 // parameter of F.
2240 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002241 Candidate.Conversions[ArgIdx]
2242 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002243 SuppressUserConversions, ForceRValue,
2244 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002245 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002246 == ImplicitConversionSequence::BadConversion) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002247 // 13.3.3.1-p10 If several different sequences of conversions exist that
2248 // each convert the argument to the parameter type, the implicit conversion
2249 // sequence associated with the parameter is defined to be the unique conversion
2250 // sequence designated the ambiguous conversion sequence. For the purpose of
2251 // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2252 // conversion sequence is treated as a user-defined sequence that is
2253 // indistinguishable from any other user-defined conversion sequence
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002254 if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002255 Candidate.Conversions[ArgIdx].ConversionKind =
2256 ImplicitConversionSequence::UserDefinedConversion;
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002257 // Set the conversion function to one of them. As due to ambiguity,
2258 // they carry the same weight and is needed for overload resolution
2259 // later.
2260 Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2261 Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2262 }
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002263 else {
2264 Candidate.Viable = false;
2265 break;
2266 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002267 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002268 } else {
2269 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2270 // argument for which there is no corresponding parameter is
2271 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002272 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002273 = ImplicitConversionSequence::EllipsisConversion;
2274 }
2275 }
2276}
2277
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002278/// \brief Add all of the function declarations in the given function set to
2279/// the overload canddiate set.
2280void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2281 Expr **Args, unsigned NumArgs,
2282 OverloadCandidateSet& CandidateSet,
2283 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002284 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002285 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002286 F != FEnd; ++F) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002287 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2288 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2289 AddMethodCandidate(cast<CXXMethodDecl>(FD),
2290 Args[0], Args + 1, NumArgs - 1,
2291 CandidateSet, SuppressUserConversions);
2292 else
2293 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2294 SuppressUserConversions);
2295 } else {
2296 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2297 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2298 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2299 AddMethodTemplateCandidate(FunTmpl,
Douglas Gregor89026b52009-06-30 23:57:56 +00002300 /*FIXME: explicit args */false, 0, 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002301 Args[0], Args + 1, NumArgs - 1,
2302 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002303 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002304 else
2305 AddTemplateOverloadCandidate(FunTmpl,
2306 /*FIXME: explicit args */false, 0, 0,
2307 Args, NumArgs, CandidateSet,
2308 SuppressUserConversions);
2309 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002310 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002311}
2312
Douglas Gregor436424c2008-11-18 23:14:02 +00002313/// AddMethodCandidate - Adds the given C++ member function to the set
2314/// of candidate functions, using the given function call arguments
2315/// and the object argument (@c Object). For example, in a call
2316/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2317/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2318/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002319/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2320/// a slightly hacky way to implement the overloading rules for elidable copy
2321/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002322void
Douglas Gregor436424c2008-11-18 23:14:02 +00002323Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2324 Expr **Args, unsigned NumArgs,
2325 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002326 bool SuppressUserConversions, bool ForceRValue) {
2327 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002328 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002329 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002330 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor436424c2008-11-18 23:14:02 +00002331 "Use AddConversionCandidate for conversion functions");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002332 assert(!isa<CXXConstructorDecl>(Method) &&
2333 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002334
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002335 if (!CandidateSet.isNewCandidate(Method))
2336 return;
2337
Douglas Gregor436424c2008-11-18 23:14:02 +00002338 // Add this candidate
2339 CandidateSet.push_back(OverloadCandidate());
2340 OverloadCandidate& Candidate = CandidateSet.back();
2341 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002342 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002343 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002344
2345 unsigned NumArgsInProto = Proto->getNumArgs();
2346
2347 // (C++ 13.3.2p2): A candidate function having fewer than m
2348 // parameters is viable only if it has an ellipsis in its parameter
2349 // list (8.3.5).
2350 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2351 Candidate.Viable = false;
2352 return;
2353 }
2354
2355 // (C++ 13.3.2p2): A candidate function having more than m parameters
2356 // is viable only if the (m+1)st parameter has a default argument
2357 // (8.3.6). For the purposes of overload resolution, the
2358 // parameter list is truncated on the right, so that there are
2359 // exactly m parameters.
2360 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2361 if (NumArgs < MinRequiredArgs) {
2362 // Not enough arguments.
2363 Candidate.Viable = false;
2364 return;
2365 }
2366
2367 Candidate.Viable = true;
2368 Candidate.Conversions.resize(NumArgs + 1);
2369
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002370 if (Method->isStatic() || !Object)
2371 // The implicit object argument is ignored.
2372 Candidate.IgnoreObjectArgument = true;
2373 else {
2374 // Determine the implicit conversion sequence for the object
2375 // parameter.
2376 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
Mike Stump11289f42009-09-09 15:08:12 +00002377 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002378 == ImplicitConversionSequence::BadConversion) {
2379 Candidate.Viable = false;
2380 return;
2381 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002382 }
2383
2384 // Determine the implicit conversion sequences for each of the
2385 // arguments.
2386 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2387 if (ArgIdx < NumArgsInProto) {
2388 // (C++ 13.3.2p3): for F to be a viable function, there shall
2389 // exist for each argument an implicit conversion sequence
2390 // (13.3.3.1) that converts that argument to the corresponding
2391 // parameter of F.
2392 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002393 Candidate.Conversions[ArgIdx + 1]
2394 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002395 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002396 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002397 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002398 == ImplicitConversionSequence::BadConversion) {
2399 Candidate.Viable = false;
2400 break;
2401 }
2402 } else {
2403 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2404 // argument for which there is no corresponding parameter is
2405 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002406 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002407 = ImplicitConversionSequence::EllipsisConversion;
2408 }
2409 }
2410}
2411
Douglas Gregor97628d62009-08-21 00:16:32 +00002412/// \brief Add a C++ member function template as a candidate to the candidate
2413/// set, using template argument deduction to produce an appropriate member
2414/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002415void
Douglas Gregor97628d62009-08-21 00:16:32 +00002416Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2417 bool HasExplicitTemplateArgs,
2418 const TemplateArgument *ExplicitTemplateArgs,
2419 unsigned NumExplicitTemplateArgs,
2420 Expr *Object, Expr **Args, unsigned NumArgs,
2421 OverloadCandidateSet& CandidateSet,
2422 bool SuppressUserConversions,
2423 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002424 if (!CandidateSet.isNewCandidate(MethodTmpl))
2425 return;
2426
Douglas Gregor97628d62009-08-21 00:16:32 +00002427 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002428 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002429 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002430 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002431 // candidate functions in the usual way.113) A given name can refer to one
2432 // or more function templates and also to a set of overloaded non-template
2433 // functions. In such a case, the candidate functions generated from each
2434 // function template are combined with the set of non-template candidate
2435 // functions.
2436 TemplateDeductionInfo Info(Context);
2437 FunctionDecl *Specialization = 0;
2438 if (TemplateDeductionResult Result
2439 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2440 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2441 Args, NumArgs, Specialization, Info)) {
2442 // FIXME: Record what happened with template argument deduction, so
2443 // that we can give the user a beautiful diagnostic.
2444 (void)Result;
2445 return;
2446 }
Mike Stump11289f42009-09-09 15:08:12 +00002447
Douglas Gregor97628d62009-08-21 00:16:32 +00002448 // Add the function template specialization produced by template argument
2449 // deduction as a candidate.
2450 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002451 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002452 "Specialization is not a member function?");
Mike Stump11289f42009-09-09 15:08:12 +00002453 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002454 CandidateSet, SuppressUserConversions, ForceRValue);
2455}
2456
Douglas Gregor05155d82009-08-21 23:19:43 +00002457/// \brief Add a C++ function template specialization as a candidate
2458/// in the candidate set, using template argument deduction to produce
2459/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002460void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002461Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor89026b52009-06-30 23:57:56 +00002462 bool HasExplicitTemplateArgs,
2463 const TemplateArgument *ExplicitTemplateArgs,
2464 unsigned NumExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002465 Expr **Args, unsigned NumArgs,
2466 OverloadCandidateSet& CandidateSet,
2467 bool SuppressUserConversions,
2468 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002469 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2470 return;
2471
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002472 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002473 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002474 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002475 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002476 // candidate functions in the usual way.113) A given name can refer to one
2477 // or more function templates and also to a set of overloaded non-template
2478 // functions. In such a case, the candidate functions generated from each
2479 // function template are combined with the set of non-template candidate
2480 // functions.
2481 TemplateDeductionInfo Info(Context);
2482 FunctionDecl *Specialization = 0;
2483 if (TemplateDeductionResult Result
Douglas Gregor89026b52009-06-30 23:57:56 +00002484 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2485 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2486 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002487 // FIXME: Record what happened with template argument deduction, so
2488 // that we can give the user a beautiful diagnostic.
2489 (void)Result;
2490 return;
2491 }
Mike Stump11289f42009-09-09 15:08:12 +00002492
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002493 // Add the function template specialization produced by template argument
2494 // deduction as a candidate.
2495 assert(Specialization && "Missing function template specialization?");
2496 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2497 SuppressUserConversions, ForceRValue);
2498}
Mike Stump11289f42009-09-09 15:08:12 +00002499
Douglas Gregora1f013e2008-11-07 22:36:19 +00002500/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002501/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002502/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002503/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002504/// (which may or may not be the same type as the type that the
2505/// conversion function produces).
2506void
2507Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2508 Expr *From, QualType ToType,
2509 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002510 assert(!Conversion->getDescribedFunctionTemplate() &&
2511 "Conversion function templates use AddTemplateConversionCandidate");
2512
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002513 if (!CandidateSet.isNewCandidate(Conversion))
2514 return;
2515
Douglas Gregora1f013e2008-11-07 22:36:19 +00002516 // Add this candidate
2517 CandidateSet.push_back(OverloadCandidate());
2518 OverloadCandidate& Candidate = CandidateSet.back();
2519 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002520 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002521 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002522 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00002523 Candidate.FinalConversion.FromTypePtr
Douglas Gregora1f013e2008-11-07 22:36:19 +00002524 = Conversion->getConversionType().getAsOpaquePtr();
2525 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2526
Douglas Gregor436424c2008-11-18 23:14:02 +00002527 // Determine the implicit conversion sequence for the implicit
2528 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002529 Candidate.Viable = true;
2530 Candidate.Conversions.resize(1);
Douglas Gregor436424c2008-11-18 23:14:02 +00002531 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002532 // Conversion functions to a different type in the base class is visible in
2533 // the derived class. So, a derived to base conversion should not participate
2534 // in overload resolution.
2535 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2536 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump11289f42009-09-09 15:08:12 +00002537 if (Candidate.Conversions[0].ConversionKind
Douglas Gregora1f013e2008-11-07 22:36:19 +00002538 == ImplicitConversionSequence::BadConversion) {
2539 Candidate.Viable = false;
2540 return;
2541 }
2542
2543 // To determine what the conversion from the result of calling the
2544 // conversion function to the type we're eventually trying to
2545 // convert to (ToType), we need to synthesize a call to the
2546 // conversion function and attempt copy initialization from it. This
2547 // makes sure that we get the right semantics with respect to
2548 // lvalues/rvalues and the type. Fortunately, we can allocate this
2549 // call on the stack and we don't need its arguments to be
2550 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002551 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregora1f013e2008-11-07 22:36:19 +00002552 SourceLocation());
2553 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Anders Carlssona2615922009-07-31 00:48:10 +00002554 CastExpr::CK_Unknown,
Douglas Gregora11693b2008-11-12 17:17:38 +00002555 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002556
2557 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002558 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2559 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002560 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002561 Conversion->getConversionType().getNonReferenceType(),
2562 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002563 ImplicitConversionSequence ICS =
2564 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002565 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002566 /*ForceRValue=*/false,
2567 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002568
Douglas Gregora1f013e2008-11-07 22:36:19 +00002569 switch (ICS.ConversionKind) {
2570 case ImplicitConversionSequence::StandardConversion:
2571 Candidate.FinalConversion = ICS.Standard;
2572 break;
2573
2574 case ImplicitConversionSequence::BadConversion:
2575 Candidate.Viable = false;
2576 break;
2577
2578 default:
Mike Stump11289f42009-09-09 15:08:12 +00002579 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002580 "Can only end up with a standard conversion sequence or failure");
2581 }
2582}
2583
Douglas Gregor05155d82009-08-21 23:19:43 +00002584/// \brief Adds a conversion function template specialization
2585/// candidate to the overload set, using template argument deduction
2586/// to deduce the template arguments of the conversion function
2587/// template from the type that we are converting to (C++
2588/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002589void
Douglas Gregor05155d82009-08-21 23:19:43 +00002590Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2591 Expr *From, QualType ToType,
2592 OverloadCandidateSet &CandidateSet) {
2593 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2594 "Only conversion function templates permitted here");
2595
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002596 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2597 return;
2598
Douglas Gregor05155d82009-08-21 23:19:43 +00002599 TemplateDeductionInfo Info(Context);
2600 CXXConversionDecl *Specialization = 0;
2601 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002602 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002603 Specialization, Info)) {
2604 // FIXME: Record what happened with template argument deduction, so
2605 // that we can give the user a beautiful diagnostic.
2606 (void)Result;
2607 return;
2608 }
Mike Stump11289f42009-09-09 15:08:12 +00002609
Douglas Gregor05155d82009-08-21 23:19:43 +00002610 // Add the conversion function template specialization produced by
2611 // template argument deduction as a candidate.
2612 assert(Specialization && "Missing function template specialization?");
2613 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2614}
2615
Douglas Gregorab7897a2008-11-19 22:57:39 +00002616/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2617/// converts the given @c Object to a function pointer via the
2618/// conversion function @c Conversion, and then attempts to call it
2619/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2620/// the type of function that we'll eventually be calling.
2621void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002622 const FunctionProtoType *Proto,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002623 Expr *Object, Expr **Args, unsigned NumArgs,
2624 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002625 if (!CandidateSet.isNewCandidate(Conversion))
2626 return;
2627
Douglas Gregorab7897a2008-11-19 22:57:39 +00002628 CandidateSet.push_back(OverloadCandidate());
2629 OverloadCandidate& Candidate = CandidateSet.back();
2630 Candidate.Function = 0;
2631 Candidate.Surrogate = Conversion;
2632 Candidate.Viable = true;
2633 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002634 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002635 Candidate.Conversions.resize(NumArgs + 1);
2636
2637 // Determine the implicit conversion sequence for the implicit
2638 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002639 ImplicitConversionSequence ObjectInit
Douglas Gregorab7897a2008-11-19 22:57:39 +00002640 = TryObjectArgumentInitialization(Object, Conversion);
2641 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2642 Candidate.Viable = false;
2643 return;
2644 }
2645
2646 // The first conversion is actually a user-defined conversion whose
2647 // first conversion is ObjectInit's standard conversion (which is
2648 // effectively a reference binding). Record it as such.
Mike Stump11289f42009-09-09 15:08:12 +00002649 Candidate.Conversions[0].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002650 = ImplicitConversionSequence::UserDefinedConversion;
2651 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2652 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002653 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002654 = Candidate.Conversions[0].UserDefined.Before;
2655 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2656
Mike Stump11289f42009-09-09 15:08:12 +00002657 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002658 unsigned NumArgsInProto = Proto->getNumArgs();
2659
2660 // (C++ 13.3.2p2): A candidate function having fewer than m
2661 // parameters is viable only if it has an ellipsis in its parameter
2662 // list (8.3.5).
2663 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2664 Candidate.Viable = false;
2665 return;
2666 }
2667
2668 // Function types don't have any default arguments, so just check if
2669 // we have enough arguments.
2670 if (NumArgs < NumArgsInProto) {
2671 // Not enough arguments.
2672 Candidate.Viable = false;
2673 return;
2674 }
2675
2676 // Determine the implicit conversion sequences for each of the
2677 // arguments.
2678 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2679 if (ArgIdx < NumArgsInProto) {
2680 // (C++ 13.3.2p3): for F to be a viable function, there shall
2681 // exist for each argument an implicit conversion sequence
2682 // (13.3.3.1) that converts that argument to the corresponding
2683 // parameter of F.
2684 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002685 Candidate.Conversions[ArgIdx + 1]
2686 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002687 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002688 /*ForceRValue=*/false,
2689 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002690 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002691 == ImplicitConversionSequence::BadConversion) {
2692 Candidate.Viable = false;
2693 break;
2694 }
2695 } else {
2696 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2697 // argument for which there is no corresponding parameter is
2698 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002699 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002700 = ImplicitConversionSequence::EllipsisConversion;
2701 }
2702 }
2703}
2704
Mike Stump87c57ac2009-05-16 07:39:55 +00002705// FIXME: This will eventually be removed, once we've migrated all of the
2706// operator overloading logic over to the scheme used by binary operators, which
2707// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002708void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002709 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002710 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002711 OverloadCandidateSet& CandidateSet,
2712 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002713 FunctionSet Functions;
2714
2715 QualType T1 = Args[0]->getType();
2716 QualType T2;
2717 if (NumArgs > 1)
2718 T2 = Args[1]->getType();
2719
2720 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002721 if (S)
2722 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002723 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2724 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2725 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2726 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2727}
2728
2729/// \brief Add overload candidates for overloaded operators that are
2730/// member functions.
2731///
2732/// Add the overloaded operator candidates that are member functions
2733/// for the operator Op that was used in an operator expression such
2734/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2735/// CandidateSet will store the added overload candidates. (C++
2736/// [over.match.oper]).
2737void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2738 SourceLocation OpLoc,
2739 Expr **Args, unsigned NumArgs,
2740 OverloadCandidateSet& CandidateSet,
2741 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002742 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2743
2744 // C++ [over.match.oper]p3:
2745 // For a unary operator @ with an operand of a type whose
2746 // cv-unqualified version is T1, and for a binary operator @ with
2747 // a left operand of a type whose cv-unqualified version is T1 and
2748 // a right operand of a type whose cv-unqualified version is T2,
2749 // three sets of candidate functions, designated member
2750 // candidates, non-member candidates and built-in candidates, are
2751 // constructed as follows:
2752 QualType T1 = Args[0]->getType();
2753 QualType T2;
2754 if (NumArgs > 1)
2755 T2 = Args[1]->getType();
2756
2757 // -- If T1 is a class type, the set of member candidates is the
2758 // result of the qualified lookup of T1::operator@
2759 // (13.3.1.1.1); otherwise, the set of member candidates is
2760 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002761 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002762 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00002763 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002764 return;
Mike Stump11289f42009-09-09 15:08:12 +00002765
John McCall9f3059a2009-10-09 21:13:30 +00002766 LookupResult Operators;
2767 LookupQualifiedName(Operators, T1Rec->getDecl(), OpName,
2768 LookupOrdinaryName, false);
Mike Stump11289f42009-09-09 15:08:12 +00002769 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002770 OperEnd = Operators.end();
2771 Oper != OperEnd;
Douglas Gregor4aa2dc42009-10-14 16:50:13 +00002772 ++Oper) {
2773 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Oper)) {
2774 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
2775 /*SuppressUserConversions=*/false);
2776 continue;
2777 }
2778
2779 assert(isa<FunctionTemplateDecl>(*Oper) &&
2780 isa<CXXMethodDecl>(cast<FunctionTemplateDecl>(*Oper)
2781 ->getTemplatedDecl()) &&
2782 "Expected a member function template");
2783 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Oper), false, 0, 0,
2784 Args[0], Args+1, NumArgs - 1, CandidateSet,
2785 /*SuppressUserConversions=*/false);
2786 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002787 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002788}
2789
Douglas Gregora11693b2008-11-12 17:17:38 +00002790/// AddBuiltinCandidate - Add a candidate for a built-in
2791/// operator. ResultTy and ParamTys are the result and parameter types
2792/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00002793/// arguments being passed to the candidate. IsAssignmentOperator
2794/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00002795/// operator. NumContextualBoolArguments is the number of arguments
2796/// (at the beginning of the argument list) that will be contextually
2797/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00002798void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00002799 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00002800 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002801 bool IsAssignmentOperator,
2802 unsigned NumContextualBoolArguments) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002803 // Add this candidate
2804 CandidateSet.push_back(OverloadCandidate());
2805 OverloadCandidate& Candidate = CandidateSet.back();
2806 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00002807 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002808 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00002809 Candidate.BuiltinTypes.ResultTy = ResultTy;
2810 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2811 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2812
2813 // Determine the implicit conversion sequences for each of the
2814 // arguments.
2815 Candidate.Viable = true;
2816 Candidate.Conversions.resize(NumArgs);
2817 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00002818 // C++ [over.match.oper]p4:
2819 // For the built-in assignment operators, conversions of the
2820 // left operand are restricted as follows:
2821 // -- no temporaries are introduced to hold the left operand, and
2822 // -- no user-defined conversions are applied to the left
2823 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00002824 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00002825 //
2826 // We block these conversions by turning off user-defined
2827 // conversions, since that is the only way that initialization of
2828 // a reference to a non-class type can occur from something that
2829 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002830 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00002831 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00002832 "Contextual conversion to bool requires bool type");
2833 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2834 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002835 Candidate.Conversions[ArgIdx]
2836 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00002837 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00002838 /*ForceRValue=*/false,
2839 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002840 }
Mike Stump11289f42009-09-09 15:08:12 +00002841 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002842 == ImplicitConversionSequence::BadConversion) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002843 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002844 break;
2845 }
Douglas Gregora11693b2008-11-12 17:17:38 +00002846 }
2847}
2848
2849/// BuiltinCandidateTypeSet - A set of types that will be used for the
2850/// candidate operator functions for built-in operators (C++
2851/// [over.built]). The types are separated into pointer types and
2852/// enumeration types.
2853class BuiltinCandidateTypeSet {
2854 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002855 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00002856
2857 /// PointerTypes - The set of pointer types that will be used in the
2858 /// built-in candidates.
2859 TypeSet PointerTypes;
2860
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002861 /// MemberPointerTypes - The set of member pointer types that will be
2862 /// used in the built-in candidates.
2863 TypeSet MemberPointerTypes;
2864
Douglas Gregora11693b2008-11-12 17:17:38 +00002865 /// EnumerationTypes - The set of enumeration types that will be
2866 /// used in the built-in candidates.
2867 TypeSet EnumerationTypes;
2868
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002869 /// Sema - The semantic analysis instance where we are building the
2870 /// candidate type set.
2871 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00002872
Douglas Gregora11693b2008-11-12 17:17:38 +00002873 /// Context - The AST context in which we will build the type sets.
2874 ASTContext &Context;
2875
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002876 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2877 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002878
2879public:
2880 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002881 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00002882
Mike Stump11289f42009-09-09 15:08:12 +00002883 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002884 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00002885
Douglas Gregor5fb53972009-01-14 15:45:31 +00002886 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00002887 bool AllowExplicitConversions,
2888 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00002889
2890 /// pointer_begin - First pointer type found;
2891 iterator pointer_begin() { return PointerTypes.begin(); }
2892
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002893 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002894 iterator pointer_end() { return PointerTypes.end(); }
2895
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002896 /// member_pointer_begin - First member pointer type found;
2897 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2898
2899 /// member_pointer_end - Past the last member pointer type found;
2900 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2901
Douglas Gregora11693b2008-11-12 17:17:38 +00002902 /// enumeration_begin - First enumeration type found;
2903 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2904
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002905 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002906 iterator enumeration_end() { return EnumerationTypes.end(); }
2907};
2908
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002909/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00002910/// the set of pointer types along with any more-qualified variants of
2911/// that type. For example, if @p Ty is "int const *", this routine
2912/// will add "int const *", "int const volatile *", "int const
2913/// restrict *", and "int const volatile restrict *" to the set of
2914/// pointer types. Returns true if the add of @p Ty itself succeeded,
2915/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00002916///
2917/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002918bool
2919BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
John McCall8ccfcb52009-09-24 19:53:00 +00002920
Douglas Gregora11693b2008-11-12 17:17:38 +00002921 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002922 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00002923 return false;
2924
John McCall8ccfcb52009-09-24 19:53:00 +00002925 const PointerType *PointerTy = Ty->getAs<PointerType>();
2926 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00002927
John McCall8ccfcb52009-09-24 19:53:00 +00002928 QualType PointeeTy = PointerTy->getPointeeType();
2929 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
2930
2931 // Iterate through all strict supersets of BaseCVR.
2932 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
2933 if ((CVR | BaseCVR) != CVR) continue;
2934
2935 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
2936 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00002937 }
2938
2939 return true;
2940}
2941
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002942/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2943/// to the set of pointer types along with any more-qualified variants of
2944/// that type. For example, if @p Ty is "int const *", this routine
2945/// will add "int const *", "int const volatile *", "int const
2946/// restrict *", and "int const volatile restrict *" to the set of
2947/// pointer types. Returns true if the add of @p Ty itself succeeded,
2948/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00002949///
2950/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002951bool
2952BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2953 QualType Ty) {
2954 // Insert this type.
2955 if (!MemberPointerTypes.insert(Ty))
2956 return false;
2957
John McCall8ccfcb52009-09-24 19:53:00 +00002958 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
2959 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002960
John McCall8ccfcb52009-09-24 19:53:00 +00002961 QualType PointeeTy = PointerTy->getPointeeType();
2962 const Type *ClassTy = PointerTy->getClass();
2963
2964 // Iterate through all strict supersets of the pointee type's CVR
2965 // qualifiers.
2966 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
2967 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
2968 if ((CVR | BaseCVR) != CVR) continue;
2969
2970 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
2971 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002972 }
2973
2974 return true;
2975}
2976
Douglas Gregora11693b2008-11-12 17:17:38 +00002977/// AddTypesConvertedFrom - Add each of the types to which the type @p
2978/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002979/// primarily interested in pointer types and enumeration types. We also
2980/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002981/// AllowUserConversions is true if we should look at the conversion
2982/// functions of a class type, and AllowExplicitConversions if we
2983/// should also include the explicit conversion functions of a class
2984/// type.
Mike Stump11289f42009-09-09 15:08:12 +00002985void
Douglas Gregor5fb53972009-01-14 15:45:31 +00002986BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2987 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00002988 bool AllowExplicitConversions,
2989 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002990 // Only deal with canonical types.
2991 Ty = Context.getCanonicalType(Ty);
2992
2993 // Look through reference types; they aren't part of the type of an
2994 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002995 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00002996 Ty = RefTy->getPointeeType();
2997
2998 // We don't care about qualifiers on the type.
2999 Ty = Ty.getUnqualifiedType();
3000
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003001 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003002 QualType PointeeTy = PointerTy->getPointeeType();
3003
3004 // Insert our type, and its more-qualified variants, into the set
3005 // of types.
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003006 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003007 return;
3008
3009 // Add 'cv void*' to our set of types.
3010 if (!Ty->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003011 QualType QualVoid
John McCall8ccfcb52009-09-24 19:53:00 +00003012 = Context.getCVRQualifiedType(Context.VoidTy,
3013 PointeeTy.getCVRQualifiers());
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003014 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregora11693b2008-11-12 17:17:38 +00003015 }
3016
3017 // If this is a pointer to a class type, add pointers to its bases
3018 // (with the same level of cv-qualification as the original
3019 // derived class, of course).
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003020 if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003021 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
3022 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3023 Base != ClassDecl->bases_end(); ++Base) {
3024 QualType BaseTy = Context.getCanonicalType(Base->getType());
John McCall8ccfcb52009-09-24 19:53:00 +00003025 BaseTy = Context.getCVRQualifiedType(BaseTy.getUnqualifiedType(),
3026 PointeeTy.getCVRQualifiers());
Douglas Gregora11693b2008-11-12 17:17:38 +00003027 // Add the pointer type, recursively, so that we get all of
3028 // the indirect base classes, too.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003029 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false,
3030 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003031 }
3032 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003033 } else if (Ty->isMemberPointerType()) {
3034 // Member pointers are far easier, since the pointee can't be converted.
3035 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3036 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003037 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003038 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003039 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003040 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003041 if (SemaRef.RequireCompleteType(SourceLocation(), Ty, 0)) {
3042 // No conversion functions in incomplete types.
3043 return;
3044 }
Mike Stump11289f42009-09-09 15:08:12 +00003045
Douglas Gregora11693b2008-11-12 17:17:38 +00003046 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003047 OverloadedFunctionDecl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003048 = ClassDecl->getVisibleConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00003049 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregora11693b2008-11-12 17:17:38 +00003050 = Conversions->function_begin();
3051 Func != Conversions->function_end(); ++Func) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003052 CXXConversionDecl *Conv;
3053 FunctionTemplateDecl *ConvTemplate;
3054 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
3055
Mike Stump11289f42009-09-09 15:08:12 +00003056 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003057 // about which builtin types we can convert to.
3058 if (ConvTemplate)
3059 continue;
3060
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003061 if (AllowExplicitConversions || !Conv->isExplicit()) {
3062 AddTypesConvertedFrom(Conv->getConversionType(), false, false,
3063 VisibleQuals);
3064 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003065 }
3066 }
3067 }
3068}
3069
Douglas Gregor84605ae2009-08-24 13:43:27 +00003070/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3071/// the volatile- and non-volatile-qualified assignment operators for the
3072/// given type to the candidate set.
3073static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3074 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003075 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003076 unsigned NumArgs,
3077 OverloadCandidateSet &CandidateSet) {
3078 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003079
Douglas Gregor84605ae2009-08-24 13:43:27 +00003080 // T& operator=(T&, T)
3081 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3082 ParamTypes[1] = T;
3083 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3084 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003085
Douglas Gregor84605ae2009-08-24 13:43:27 +00003086 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3087 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003088 ParamTypes[0]
3089 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003090 ParamTypes[1] = T;
3091 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003092 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003093 }
3094}
Mike Stump11289f42009-09-09 15:08:12 +00003095
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003096/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers
3097/// , if any, found in visible type conversion functions found in ArgExpr's
3098/// type.
3099static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3100 Qualifiers VRQuals;
3101 const RecordType *TyRec;
3102 if (const MemberPointerType *RHSMPType =
3103 ArgExpr->getType()->getAs<MemberPointerType>())
3104 TyRec = cast<RecordType>(RHSMPType->getClass());
3105 else
3106 TyRec = ArgExpr->getType()->getAs<RecordType>();
3107 if (!TyRec) {
3108 // Just to be safe, asssume the worst case.
3109 VRQuals.addVolatile();
3110 VRQuals.addRestrict();
3111 return VRQuals;
3112 }
3113
3114 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
3115 OverloadedFunctionDecl *Conversions =
3116 ClassDecl->getVisibleConversionFunctions();
3117
3118 for (OverloadedFunctionDecl::function_iterator Func
3119 = Conversions->function_begin();
3120 Func != Conversions->function_end(); ++Func) {
3121 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*Func)) {
3122 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3123 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3124 CanTy = ResTypeRef->getPointeeType();
3125 // Need to go down the pointer/mempointer chain and add qualifiers
3126 // as see them.
3127 bool done = false;
3128 while (!done) {
3129 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3130 CanTy = ResTypePtr->getPointeeType();
3131 else if (const MemberPointerType *ResTypeMPtr =
3132 CanTy->getAs<MemberPointerType>())
3133 CanTy = ResTypeMPtr->getPointeeType();
3134 else
3135 done = true;
3136 if (CanTy.isVolatileQualified())
3137 VRQuals.addVolatile();
3138 if (CanTy.isRestrictQualified())
3139 VRQuals.addRestrict();
3140 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3141 return VRQuals;
3142 }
3143 }
3144 }
3145 return VRQuals;
3146}
3147
Douglas Gregord08452f2008-11-19 15:42:04 +00003148/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3149/// operator overloads to the candidate set (C++ [over.built]), based
3150/// on the operator @p Op and the arguments given. For example, if the
3151/// operator is a binary '+', this routine might add "int
3152/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003153void
Mike Stump11289f42009-09-09 15:08:12 +00003154Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregord08452f2008-11-19 15:42:04 +00003155 Expr **Args, unsigned NumArgs,
3156 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003157 // The set of "promoted arithmetic types", which are the arithmetic
3158 // types are that preserved by promotion (C++ [over.built]p2). Note
3159 // that the first few of these types are the promoted integral
3160 // types; these types need to be first.
3161 // FIXME: What about complex?
3162 const unsigned FirstIntegralType = 0;
3163 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003164 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003165 LastPromotedIntegralType = 13;
3166 const unsigned FirstPromotedArithmeticType = 7,
3167 LastPromotedArithmeticType = 16;
3168 const unsigned NumArithmeticTypes = 16;
3169 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003170 Context.BoolTy, Context.CharTy, Context.WCharTy,
3171// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003172 Context.SignedCharTy, Context.ShortTy,
3173 Context.UnsignedCharTy, Context.UnsignedShortTy,
3174 Context.IntTy, Context.LongTy, Context.LongLongTy,
3175 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3176 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3177 };
3178
3179 // Find all of the types that the arguments can convert to, but only
3180 // if the operator we're looking at has built-in operator candidates
3181 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003182 Qualifiers VisibleTypeConversionsQuals;
3183 VisibleTypeConversionsQuals.addConst();
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003184 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003185 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3186 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003187 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003188 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003189 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003190 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003191 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003192 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3193
3194 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003195 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3196 true,
3197 (Op == OO_Exclaim ||
3198 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003199 Op == OO_PipePipe),
3200 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003201 }
3202
3203 bool isComparison = false;
3204 switch (Op) {
3205 case OO_None:
3206 case NUM_OVERLOADED_OPERATORS:
3207 assert(false && "Expected an overloaded operator");
3208 break;
3209
Douglas Gregord08452f2008-11-19 15:42:04 +00003210 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003211 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003212 goto UnaryStar;
3213 else
3214 goto BinaryStar;
3215 break;
3216
3217 case OO_Plus: // '+' is either unary or binary
3218 if (NumArgs == 1)
3219 goto UnaryPlus;
3220 else
3221 goto BinaryPlus;
3222 break;
3223
3224 case OO_Minus: // '-' is either unary or binary
3225 if (NumArgs == 1)
3226 goto UnaryMinus;
3227 else
3228 goto BinaryMinus;
3229 break;
3230
3231 case OO_Amp: // '&' is either unary or binary
3232 if (NumArgs == 1)
3233 goto UnaryAmp;
3234 else
3235 goto BinaryAmp;
3236
3237 case OO_PlusPlus:
3238 case OO_MinusMinus:
3239 // C++ [over.built]p3:
3240 //
3241 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3242 // is either volatile or empty, there exist candidate operator
3243 // functions of the form
3244 //
3245 // VQ T& operator++(VQ T&);
3246 // T operator++(VQ T&, int);
3247 //
3248 // C++ [over.built]p4:
3249 //
3250 // For every pair (T, VQ), where T is an arithmetic type other
3251 // than bool, and VQ is either volatile or empty, there exist
3252 // candidate operator functions of the form
3253 //
3254 // VQ T& operator--(VQ T&);
3255 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003256 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003257 Arith < NumArithmeticTypes; ++Arith) {
3258 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003259 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003260 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003261
3262 // Non-volatile version.
3263 if (NumArgs == 1)
3264 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3265 else
3266 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003267 // heuristic to reduce number of builtin candidates in the set.
3268 // Add volatile version only if there are conversions to a volatile type.
3269 if (VisibleTypeConversionsQuals.hasVolatile()) {
3270 // Volatile version
3271 ParamTypes[0]
3272 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3273 if (NumArgs == 1)
3274 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3275 else
3276 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3277 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003278 }
3279
3280 // C++ [over.built]p5:
3281 //
3282 // For every pair (T, VQ), where T is a cv-qualified or
3283 // cv-unqualified object type, and VQ is either volatile or
3284 // empty, there exist candidate operator functions of the form
3285 //
3286 // T*VQ& operator++(T*VQ&);
3287 // T*VQ& operator--(T*VQ&);
3288 // T* operator++(T*VQ&, int);
3289 // T* operator--(T*VQ&, int);
3290 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3291 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3292 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003293 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003294 continue;
3295
Mike Stump11289f42009-09-09 15:08:12 +00003296 QualType ParamTypes[2] = {
3297 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003298 };
Mike Stump11289f42009-09-09 15:08:12 +00003299
Douglas Gregord08452f2008-11-19 15:42:04 +00003300 // Without volatile
3301 if (NumArgs == 1)
3302 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3303 else
3304 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3305
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003306 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3307 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003308 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003309 ParamTypes[0]
3310 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003311 if (NumArgs == 1)
3312 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3313 else
3314 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3315 }
3316 }
3317 break;
3318
3319 UnaryStar:
3320 // C++ [over.built]p6:
3321 // For every cv-qualified or cv-unqualified object type T, there
3322 // exist candidate operator functions of the form
3323 //
3324 // T& operator*(T*);
3325 //
3326 // C++ [over.built]p7:
3327 // For every function type T, there exist candidate operator
3328 // functions of the form
3329 // T& operator*(T*);
3330 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3331 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3332 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003333 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003334 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003335 &ParamTy, Args, 1, CandidateSet);
3336 }
3337 break;
3338
3339 UnaryPlus:
3340 // C++ [over.built]p8:
3341 // For every type T, there exist candidate operator functions of
3342 // the form
3343 //
3344 // T* operator+(T*);
3345 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3346 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3347 QualType ParamTy = *Ptr;
3348 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3349 }
Mike Stump11289f42009-09-09 15:08:12 +00003350
Douglas Gregord08452f2008-11-19 15:42:04 +00003351 // Fall through
3352
3353 UnaryMinus:
3354 // C++ [over.built]p9:
3355 // For every promoted arithmetic type T, there exist candidate
3356 // operator functions of the form
3357 //
3358 // T operator+(T);
3359 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003360 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003361 Arith < LastPromotedArithmeticType; ++Arith) {
3362 QualType ArithTy = ArithmeticTypes[Arith];
3363 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3364 }
3365 break;
3366
3367 case OO_Tilde:
3368 // C++ [over.built]p10:
3369 // For every promoted integral type T, there exist candidate
3370 // operator functions of the form
3371 //
3372 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003373 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003374 Int < LastPromotedIntegralType; ++Int) {
3375 QualType IntTy = ArithmeticTypes[Int];
3376 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3377 }
3378 break;
3379
Douglas Gregora11693b2008-11-12 17:17:38 +00003380 case OO_New:
3381 case OO_Delete:
3382 case OO_Array_New:
3383 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003384 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003385 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003386 break;
3387
3388 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003389 UnaryAmp:
3390 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003391 // C++ [over.match.oper]p3:
3392 // -- For the operator ',', the unary operator '&', or the
3393 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003394 break;
3395
Douglas Gregor84605ae2009-08-24 13:43:27 +00003396 case OO_EqualEqual:
3397 case OO_ExclaimEqual:
3398 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003399 // For every pointer to member type T, there exist candidate operator
3400 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003401 //
3402 // bool operator==(T,T);
3403 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003404 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003405 MemPtr = CandidateTypes.member_pointer_begin(),
3406 MemPtrEnd = CandidateTypes.member_pointer_end();
3407 MemPtr != MemPtrEnd;
3408 ++MemPtr) {
3409 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3410 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3411 }
Mike Stump11289f42009-09-09 15:08:12 +00003412
Douglas Gregor84605ae2009-08-24 13:43:27 +00003413 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003414
Douglas Gregora11693b2008-11-12 17:17:38 +00003415 case OO_Less:
3416 case OO_Greater:
3417 case OO_LessEqual:
3418 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003419 // C++ [over.built]p15:
3420 //
3421 // For every pointer or enumeration type T, there exist
3422 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003423 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003424 // bool operator<(T, T);
3425 // bool operator>(T, T);
3426 // bool operator<=(T, T);
3427 // bool operator>=(T, T);
3428 // bool operator==(T, T);
3429 // bool operator!=(T, T);
3430 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3431 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3432 QualType ParamTypes[2] = { *Ptr, *Ptr };
3433 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3434 }
Mike Stump11289f42009-09-09 15:08:12 +00003435 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003436 = CandidateTypes.enumeration_begin();
3437 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3438 QualType ParamTypes[2] = { *Enum, *Enum };
3439 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3440 }
3441
3442 // Fall through.
3443 isComparison = true;
3444
Douglas Gregord08452f2008-11-19 15:42:04 +00003445 BinaryPlus:
3446 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003447 if (!isComparison) {
3448 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3449
3450 // C++ [over.built]p13:
3451 //
3452 // For every cv-qualified or cv-unqualified object type T
3453 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003454 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003455 // T* operator+(T*, ptrdiff_t);
3456 // T& operator[](T*, ptrdiff_t); [BELOW]
3457 // T* operator-(T*, ptrdiff_t);
3458 // T* operator+(ptrdiff_t, T*);
3459 // T& operator[](ptrdiff_t, T*); [BELOW]
3460 //
3461 // C++ [over.built]p14:
3462 //
3463 // For every T, where T is a pointer to object type, there
3464 // exist candidate operator functions of the form
3465 //
3466 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003467 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003468 = CandidateTypes.pointer_begin();
3469 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3470 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3471
3472 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3473 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3474
3475 if (Op == OO_Plus) {
3476 // T* operator+(ptrdiff_t, T*);
3477 ParamTypes[0] = ParamTypes[1];
3478 ParamTypes[1] = *Ptr;
3479 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3480 } else {
3481 // ptrdiff_t operator-(T, T);
3482 ParamTypes[1] = *Ptr;
3483 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3484 Args, 2, CandidateSet);
3485 }
3486 }
3487 }
3488 // Fall through
3489
Douglas Gregora11693b2008-11-12 17:17:38 +00003490 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003491 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003492 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003493 // C++ [over.built]p12:
3494 //
3495 // For every pair of promoted arithmetic types L and R, there
3496 // exist candidate operator functions of the form
3497 //
3498 // LR operator*(L, R);
3499 // LR operator/(L, R);
3500 // LR operator+(L, R);
3501 // LR operator-(L, R);
3502 // bool operator<(L, R);
3503 // bool operator>(L, R);
3504 // bool operator<=(L, R);
3505 // bool operator>=(L, R);
3506 // bool operator==(L, R);
3507 // bool operator!=(L, R);
3508 //
3509 // where LR is the result of the usual arithmetic conversions
3510 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003511 //
3512 // C++ [over.built]p24:
3513 //
3514 // For every pair of promoted arithmetic types L and R, there exist
3515 // candidate operator functions of the form
3516 //
3517 // LR operator?(bool, L, R);
3518 //
3519 // where LR is the result of the usual arithmetic conversions
3520 // between types L and R.
3521 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003522 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003523 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003524 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003525 Right < LastPromotedArithmeticType; ++Right) {
3526 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003527 QualType Result
3528 = isComparison
3529 ? Context.BoolTy
3530 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003531 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3532 }
3533 }
3534 break;
3535
3536 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003537 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003538 case OO_Caret:
3539 case OO_Pipe:
3540 case OO_LessLess:
3541 case OO_GreaterGreater:
3542 // C++ [over.built]p17:
3543 //
3544 // For every pair of promoted integral types L and R, there
3545 // exist candidate operator functions of the form
3546 //
3547 // LR operator%(L, R);
3548 // LR operator&(L, R);
3549 // LR operator^(L, R);
3550 // LR operator|(L, R);
3551 // L operator<<(L, R);
3552 // L operator>>(L, R);
3553 //
3554 // where LR is the result of the usual arithmetic conversions
3555 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003556 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003557 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003558 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003559 Right < LastPromotedIntegralType; ++Right) {
3560 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3561 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3562 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003563 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003564 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3565 }
3566 }
3567 break;
3568
3569 case OO_Equal:
3570 // C++ [over.built]p20:
3571 //
3572 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003573 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003574 // empty, there exist candidate operator functions of the form
3575 //
3576 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003577 for (BuiltinCandidateTypeSet::iterator
3578 Enum = CandidateTypes.enumeration_begin(),
3579 EnumEnd = CandidateTypes.enumeration_end();
3580 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003581 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003582 CandidateSet);
3583 for (BuiltinCandidateTypeSet::iterator
3584 MemPtr = CandidateTypes.member_pointer_begin(),
3585 MemPtrEnd = CandidateTypes.member_pointer_end();
3586 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003587 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003588 CandidateSet);
3589 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003590
3591 case OO_PlusEqual:
3592 case OO_MinusEqual:
3593 // C++ [over.built]p19:
3594 //
3595 // For every pair (T, VQ), where T is any type and VQ is either
3596 // volatile or empty, there exist candidate operator functions
3597 // of the form
3598 //
3599 // T*VQ& operator=(T*VQ&, T*);
3600 //
3601 // C++ [over.built]p21:
3602 //
3603 // For every pair (T, VQ), where T is a cv-qualified or
3604 // cv-unqualified object type and VQ is either volatile or
3605 // empty, there exist candidate operator functions of the form
3606 //
3607 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3608 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3609 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3610 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3611 QualType ParamTypes[2];
3612 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3613
3614 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003615 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003616 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3617 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003618
Douglas Gregord08452f2008-11-19 15:42:04 +00003619 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3620 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003621 ParamTypes[0]
3622 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003623 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3624 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003625 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003626 }
3627 // Fall through.
3628
3629 case OO_StarEqual:
3630 case OO_SlashEqual:
3631 // C++ [over.built]p18:
3632 //
3633 // For every triple (L, VQ, R), where L is an arithmetic type,
3634 // VQ is either volatile or empty, and R is a promoted
3635 // arithmetic type, there exist candidate operator functions of
3636 // the form
3637 //
3638 // VQ L& operator=(VQ L&, R);
3639 // VQ L& operator*=(VQ L&, R);
3640 // VQ L& operator/=(VQ L&, R);
3641 // VQ L& operator+=(VQ L&, R);
3642 // VQ L& operator-=(VQ L&, R);
3643 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003644 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003645 Right < LastPromotedArithmeticType; ++Right) {
3646 QualType ParamTypes[2];
3647 ParamTypes[1] = ArithmeticTypes[Right];
3648
3649 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003650 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003651 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3652 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003653
3654 // Add this built-in operator as a candidate (VQ is 'volatile').
John McCall8ccfcb52009-09-24 19:53:00 +00003655 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003656 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003657 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3658 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003659 }
3660 }
3661 break;
3662
3663 case OO_PercentEqual:
3664 case OO_LessLessEqual:
3665 case OO_GreaterGreaterEqual:
3666 case OO_AmpEqual:
3667 case OO_CaretEqual:
3668 case OO_PipeEqual:
3669 // C++ [over.built]p22:
3670 //
3671 // For every triple (L, VQ, R), where L is an integral type, VQ
3672 // is either volatile or empty, and R is a promoted integral
3673 // type, there exist candidate operator functions of the form
3674 //
3675 // VQ L& operator%=(VQ L&, R);
3676 // VQ L& operator<<=(VQ L&, R);
3677 // VQ L& operator>>=(VQ L&, R);
3678 // VQ L& operator&=(VQ L&, R);
3679 // VQ L& operator^=(VQ L&, R);
3680 // VQ L& operator|=(VQ L&, R);
3681 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003682 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003683 Right < LastPromotedIntegralType; ++Right) {
3684 QualType ParamTypes[2];
3685 ParamTypes[1] = ArithmeticTypes[Right];
3686
3687 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003688 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003689 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3690
3691 // Add this built-in operator as a candidate (VQ is 'volatile').
3692 ParamTypes[0] = ArithmeticTypes[Left];
John McCall8ccfcb52009-09-24 19:53:00 +00003693 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003694 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003695 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3696 }
3697 }
3698 break;
3699
Douglas Gregord08452f2008-11-19 15:42:04 +00003700 case OO_Exclaim: {
3701 // C++ [over.operator]p23:
3702 //
3703 // There also exist candidate operator functions of the form
3704 //
Mike Stump11289f42009-09-09 15:08:12 +00003705 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003706 // bool operator&&(bool, bool); [BELOW]
3707 // bool operator||(bool, bool); [BELOW]
3708 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003709 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3710 /*IsAssignmentOperator=*/false,
3711 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003712 break;
3713 }
3714
Douglas Gregora11693b2008-11-12 17:17:38 +00003715 case OO_AmpAmp:
3716 case OO_PipePipe: {
3717 // C++ [over.operator]p23:
3718 //
3719 // There also exist candidate operator functions of the form
3720 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003721 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003722 // bool operator&&(bool, bool);
3723 // bool operator||(bool, bool);
3724 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003725 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3726 /*IsAssignmentOperator=*/false,
3727 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003728 break;
3729 }
3730
3731 case OO_Subscript:
3732 // C++ [over.built]p13:
3733 //
3734 // For every cv-qualified or cv-unqualified object type T there
3735 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003736 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003737 // T* operator+(T*, ptrdiff_t); [ABOVE]
3738 // T& operator[](T*, ptrdiff_t);
3739 // T* operator-(T*, ptrdiff_t); [ABOVE]
3740 // T* operator+(ptrdiff_t, T*); [ABOVE]
3741 // T& operator[](ptrdiff_t, T*);
3742 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3743 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3744 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003745 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003746 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003747
3748 // T& operator[](T*, ptrdiff_t)
3749 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3750
3751 // T& operator[](ptrdiff_t, T*);
3752 ParamTypes[0] = ParamTypes[1];
3753 ParamTypes[1] = *Ptr;
3754 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3755 }
3756 break;
3757
3758 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003759 // C++ [over.built]p11:
3760 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3761 // C1 is the same type as C2 or is a derived class of C2, T is an object
3762 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3763 // there exist candidate operator functions of the form
3764 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3765 // where CV12 is the union of CV1 and CV2.
3766 {
3767 for (BuiltinCandidateTypeSet::iterator Ptr =
3768 CandidateTypes.pointer_begin();
3769 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3770 QualType C1Ty = (*Ptr);
3771 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003772 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003773 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003774 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003775 if (!isa<RecordType>(C1))
3776 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003777 // heuristic to reduce number of builtin candidates in the set.
3778 // Add volatile/restrict version only if there are conversions to a
3779 // volatile/restrict type.
3780 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3781 continue;
3782 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3783 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003784 }
3785 for (BuiltinCandidateTypeSet::iterator
3786 MemPtr = CandidateTypes.member_pointer_begin(),
3787 MemPtrEnd = CandidateTypes.member_pointer_end();
3788 MemPtr != MemPtrEnd; ++MemPtr) {
3789 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3790 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00003791 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003792 if (C1 != C2 && !IsDerivedFrom(C1, C2))
3793 break;
3794 QualType ParamTypes[2] = { *Ptr, *MemPtr };
3795 // build CV12 T&
3796 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003797 if (!VisibleTypeConversionsQuals.hasVolatile() &&
3798 T.isVolatileQualified())
3799 continue;
3800 if (!VisibleTypeConversionsQuals.hasRestrict() &&
3801 T.isRestrictQualified())
3802 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003803 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003804 QualType ResultTy = Context.getLValueReferenceType(T);
3805 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3806 }
3807 }
3808 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003809 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003810
3811 case OO_Conditional:
3812 // Note that we don't consider the first argument, since it has been
3813 // contextually converted to bool long ago. The candidates below are
3814 // therefore added as binary.
3815 //
3816 // C++ [over.built]p24:
3817 // For every type T, where T is a pointer or pointer-to-member type,
3818 // there exist candidate operator functions of the form
3819 //
3820 // T operator?(bool, T, T);
3821 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00003822 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3823 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3824 QualType ParamTypes[2] = { *Ptr, *Ptr };
3825 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3826 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003827 for (BuiltinCandidateTypeSet::iterator Ptr =
3828 CandidateTypes.member_pointer_begin(),
3829 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3830 QualType ParamTypes[2] = { *Ptr, *Ptr };
3831 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3832 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003833 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00003834 }
3835}
3836
Douglas Gregore254f902009-02-04 00:32:51 +00003837/// \brief Add function candidates found via argument-dependent lookup
3838/// to the set of overloading candidates.
3839///
3840/// This routine performs argument-dependent name lookup based on the
3841/// given function name (which may also be an operator name) and adds
3842/// all of the overload candidates found by ADL to the overload
3843/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00003844void
Douglas Gregore254f902009-02-04 00:32:51 +00003845Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3846 Expr **Args, unsigned NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00003847 bool HasExplicitTemplateArgs,
3848 const TemplateArgument *ExplicitTemplateArgs,
3849 unsigned NumExplicitTemplateArgs,
3850 OverloadCandidateSet& CandidateSet,
3851 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003852 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00003853
Douglas Gregorcabea402009-09-22 15:41:20 +00003854 // FIXME: Should we be trafficking in canonical function decls throughout?
3855
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003856 // Record all of the function candidates that we've already
3857 // added to the overload set, so that we don't add those same
3858 // candidates a second time.
3859 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3860 CandEnd = CandidateSet.end();
3861 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003862 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003863 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003864 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3865 Functions.insert(FunTmpl);
3866 }
Douglas Gregore254f902009-02-04 00:32:51 +00003867
Douglas Gregorcabea402009-09-22 15:41:20 +00003868 // FIXME: Pass in the explicit template arguments?
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003869 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00003870
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003871 // Erase all of the candidates we already knew about.
3872 // FIXME: This is suboptimal. Is there a better way?
3873 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3874 CandEnd = CandidateSet.end();
3875 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003876 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003877 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003878 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3879 Functions.erase(FunTmpl);
3880 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003881
3882 // For each of the ADL candidates we found, add it to the overload
3883 // set.
3884 for (FunctionSet::iterator Func = Functions.begin(),
3885 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00003886 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003887 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
3888 if (HasExplicitTemplateArgs)
3889 continue;
3890
3891 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
3892 false, false, PartialOverloading);
3893 } else
Mike Stump11289f42009-09-09 15:08:12 +00003894 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00003895 HasExplicitTemplateArgs,
3896 ExplicitTemplateArgs,
3897 NumExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003898 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00003899 }
Douglas Gregore254f902009-02-04 00:32:51 +00003900}
3901
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003902/// isBetterOverloadCandidate - Determines whether the first overload
3903/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00003904bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003905Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00003906 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003907 // Define viable functions to be better candidates than non-viable
3908 // functions.
3909 if (!Cand2.Viable)
3910 return Cand1.Viable;
3911 else if (!Cand1.Viable)
3912 return false;
3913
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003914 // C++ [over.match.best]p1:
3915 //
3916 // -- if F is a static member function, ICS1(F) is defined such
3917 // that ICS1(F) is neither better nor worse than ICS1(G) for
3918 // any function G, and, symmetrically, ICS1(G) is neither
3919 // better nor worse than ICS1(F).
3920 unsigned StartArg = 0;
3921 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3922 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003923
Douglas Gregord3cb3562009-07-07 23:38:56 +00003924 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00003925 // A viable function F1 is defined to be a better function than another
3926 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00003927 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003928 unsigned NumArgs = Cand1.Conversions.size();
3929 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3930 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003931 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003932 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3933 Cand2.Conversions[ArgIdx])) {
3934 case ImplicitConversionSequence::Better:
3935 // Cand1 has a better conversion sequence.
3936 HasBetterConversion = true;
3937 break;
3938
3939 case ImplicitConversionSequence::Worse:
3940 // Cand1 can't be better than Cand2.
3941 return false;
3942
3943 case ImplicitConversionSequence::Indistinguishable:
3944 // Do nothing.
3945 break;
3946 }
3947 }
3948
Mike Stump11289f42009-09-09 15:08:12 +00003949 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00003950 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003951 if (HasBetterConversion)
3952 return true;
3953
Mike Stump11289f42009-09-09 15:08:12 +00003954 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00003955 // specialization, or, if not that,
3956 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3957 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3958 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003959
3960 // -- F1 and F2 are function template specializations, and the function
3961 // template for F1 is more specialized than the template for F2
3962 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00003963 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00003964 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3965 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00003966 if (FunctionTemplateDecl *BetterTemplate
3967 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3968 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00003969 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
3970 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00003971 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003972
Douglas Gregora1f013e2008-11-07 22:36:19 +00003973 // -- the context is an initialization by user-defined conversion
3974 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3975 // from the return type of F1 to the destination type (i.e.,
3976 // the type of the entity being initialized) is a better
3977 // conversion sequence than the standard conversion sequence
3978 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00003979 if (Cand1.Function && Cand2.Function &&
3980 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003981 isa<CXXConversionDecl>(Cand2.Function)) {
3982 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3983 Cand2.FinalConversion)) {
3984 case ImplicitConversionSequence::Better:
3985 // Cand1 has a better conversion sequence.
3986 return true;
3987
3988 case ImplicitConversionSequence::Worse:
3989 // Cand1 can't be better than Cand2.
3990 return false;
3991
3992 case ImplicitConversionSequence::Indistinguishable:
3993 // Do nothing
3994 break;
3995 }
3996 }
3997
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003998 return false;
3999}
4000
Mike Stump11289f42009-09-09 15:08:12 +00004001/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004002/// within an overload candidate set.
4003///
4004/// \param CandidateSet the set of candidate functions.
4005///
4006/// \param Loc the location of the function name (or operator symbol) for
4007/// which overload resolution occurs.
4008///
Mike Stump11289f42009-09-09 15:08:12 +00004009/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004010/// function, Best points to the candidate function found.
4011///
4012/// \returns The result of overload resolution.
Mike Stump11289f42009-09-09 15:08:12 +00004013Sema::OverloadingResult
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004014Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004015 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004016 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004017 // Find the best viable function.
4018 Best = CandidateSet.end();
4019 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4020 Cand != CandidateSet.end(); ++Cand) {
4021 if (Cand->Viable) {
4022 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4023 Best = Cand;
4024 }
4025 }
4026
4027 // If we didn't find any viable functions, abort.
4028 if (Best == CandidateSet.end())
4029 return OR_No_Viable_Function;
4030
4031 // Make sure that this function is better than every other viable
4032 // function. If not, we have an ambiguity.
4033 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4034 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004035 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004036 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00004037 !isBetterOverloadCandidate(*Best, *Cand)) {
4038 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004039 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004040 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004041 }
Mike Stump11289f42009-09-09 15:08:12 +00004042
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004043 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004044 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004045 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004046 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004047 return OR_Deleted;
4048
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004049 // C++ [basic.def.odr]p2:
4050 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004051 // when referred to from a potentially-evaluated expression. [Note: this
4052 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004053 // (clause 13), user-defined conversions (12.3.2), allocation function for
4054 // placement new (5.3.4), as well as non-default initialization (8.5).
4055 if (Best->Function)
4056 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004057 return OR_Success;
4058}
4059
4060/// PrintOverloadCandidates - When overload resolution fails, prints
4061/// diagnostic messages containing the candidates in the candidate
4062/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump11289f42009-09-09 15:08:12 +00004063void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004064Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004065 bool OnlyViable,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004066 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004067 SourceLocation OpLoc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004068 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4069 LastCand = CandidateSet.end();
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004070 bool Reported = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004071 for (; Cand != LastCand; ++Cand) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004072 if (Cand->Viable || !OnlyViable) {
4073 if (Cand->Function) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004074 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004075 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004076 // Deleted or "unavailable" function.
4077 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4078 << Cand->Function->isDeleted();
Douglas Gregor4fb9cde8e2009-09-15 20:11:42 +00004079 } else if (FunctionTemplateDecl *FunTmpl
4080 = Cand->Function->getPrimaryTemplate()) {
4081 // Function template specialization
4082 // FIXME: Give a better reason!
4083 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4084 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4085 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor171c45a2009-02-18 21:56:37 +00004086 } else {
4087 // Normal function
Fariborz Jahanian21ccf062009-09-23 00:58:07 +00004088 bool errReported = false;
4089 if (!Cand->Viable && Cand->Conversions.size() > 0) {
4090 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4091 const ImplicitConversionSequence &Conversion =
4092 Cand->Conversions[i];
4093 if ((Conversion.ConversionKind !=
4094 ImplicitConversionSequence::BadConversion) ||
4095 Conversion.ConversionFunctionSet.size() == 0)
4096 continue;
4097 Diag(Cand->Function->getLocation(),
4098 diag::err_ovl_candidate_not_viable) << (i+1);
4099 errReported = true;
4100 for (int j = Conversion.ConversionFunctionSet.size()-1;
4101 j >= 0; j--) {
4102 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4103 Diag(Func->getLocation(), diag::err_ovl_candidate);
4104 }
4105 }
4106 }
4107 if (!errReported)
4108 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor171c45a2009-02-18 21:56:37 +00004109 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00004110 } else if (Cand->IsSurrogate) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004111 // Desugar the type of the surrogate down to a function type,
4112 // retaining as many typedefs as possible while still showing
4113 // the function type (and, therefore, its parameter types).
4114 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004115 bool isLValueReference = false;
4116 bool isRValueReference = false;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004117 bool isPointer = false;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004118 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004119 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004120 FnType = FnTypeRef->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004121 isLValueReference = true;
4122 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004123 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004124 FnType = FnTypeRef->getPointeeType();
4125 isRValueReference = true;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004126 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004127 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004128 FnType = FnTypePtr->getPointeeType();
4129 isPointer = true;
4130 }
4131 // Desugar down to a function type.
John McCall9dd450b2009-09-21 23:43:11 +00004132 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004133 // Reconstruct the pointer/reference as appropriate.
4134 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004135 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4136 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004137
Douglas Gregorab7897a2008-11-19 22:57:39 +00004138 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004139 << FnType;
Douglas Gregor66950a32009-09-30 21:46:01 +00004140 } else if (OnlyViable) {
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004141 assert(Cand->Conversions.size() <= 2 &&
Fariborz Jahanian0fe5e032009-10-09 17:09:58 +00004142 "builtin-binary-operator-not-binary");
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004143 if (Cand->Conversions.size() == 1)
4144 Diag(OpLoc, diag::err_ovl_builtin_unary_candidate)
4145 << Opc << Cand->BuiltinTypes.ParamTypes[0];
4146 else
4147 Diag(OpLoc, diag::err_ovl_builtin_binary_candidate)
4148 << Opc << Cand->BuiltinTypes.ParamTypes[0]
4149 << Cand->BuiltinTypes.ParamTypes[1];
Douglas Gregora11693b2008-11-12 17:17:38 +00004150 }
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004151 else if (!Cand->Viable && !Reported) {
4152 // Non-viability might be due to ambiguous user-defined conversions,
4153 // needed for built-in operators. Report them as well, but only once
4154 // as we have typically many built-in candidates.
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004155 unsigned NoOperands = Cand->Conversions.size();
4156 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004157 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4158 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4159 ICS.ConversionFunctionSet.empty())
4160 continue;
4161 if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4162 Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4163 QualType FromTy =
4164 QualType(
4165 static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4166 Diag(OpLoc,diag::note_ambiguous_type_conversion)
4167 << FromTy << Func->getConversionType();
4168 }
4169 for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4170 FunctionDecl *Func =
4171 Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4172 Diag(Func->getLocation(),diag::err_ovl_candidate);
4173 }
4174 }
4175 Reported = true;
4176 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004177 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004178 }
4179}
4180
Douglas Gregorcd695e52008-11-10 20:40:00 +00004181/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4182/// an overloaded function (C++ [over.over]), where @p From is an
4183/// expression with overloaded function type and @p ToType is the type
4184/// we're trying to resolve to. For example:
4185///
4186/// @code
4187/// int f(double);
4188/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004189///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004190/// int (*pfd)(double) = f; // selects f(double)
4191/// @endcode
4192///
4193/// This routine returns the resulting FunctionDecl if it could be
4194/// resolved, and NULL otherwise. When @p Complain is true, this
4195/// routine will emit diagnostics if there is an error.
4196FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004197Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004198 bool Complain) {
4199 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004200 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004201 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004202 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004203 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004204 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004205 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004206 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004207 FunctionType = MemTypePtr->getPointeeType();
4208 IsMember = true;
4209 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004210
4211 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00004212 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00004213 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004214 return 0;
4215
4216 // Find the actual overloaded function declaration.
4217 OverloadedFunctionDecl *Ovl = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004218
Douglas Gregorcd695e52008-11-10 20:40:00 +00004219 // C++ [over.over]p1:
4220 // [...] [Note: any redundant set of parentheses surrounding the
4221 // overloaded function name is ignored (5.1). ]
4222 Expr *OvlExpr = From->IgnoreParens();
4223
4224 // C++ [over.over]p1:
4225 // [...] The overloaded function name can be preceded by the &
4226 // operator.
4227 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4228 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4229 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4230 }
4231
4232 // Try to dig out the overloaded function.
Douglas Gregor9b146582009-07-08 20:55:45 +00004233 FunctionTemplateDecl *FunctionTemplate = 0;
4234 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004235 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor9b146582009-07-08 20:55:45 +00004236 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
Anders Carlsson6c966c42009-10-07 22:26:29 +00004237 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(OvlExpr)) {
4238 Ovl = dyn_cast<OverloadedFunctionDecl>(ME->getMemberDecl());
4239 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(ME->getMemberDecl());
Douglas Gregor7d195b92009-10-09 22:54:25 +00004240 // FIXME: Explicit template arguments
Douglas Gregor9b146582009-07-08 20:55:45 +00004241 }
Douglas Gregor7d195b92009-10-09 22:54:25 +00004242 // FIXME: TemplateIdRefExpr?
Douglas Gregorcd695e52008-11-10 20:40:00 +00004243
Mike Stump11289f42009-09-09 15:08:12 +00004244 // If there's no overloaded function declaration or function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00004245 // we're done.
4246 if (!Ovl && !FunctionTemplate)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004247 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004248
Douglas Gregor9b146582009-07-08 20:55:45 +00004249 OverloadIterator Fun;
4250 if (Ovl)
4251 Fun = Ovl;
4252 else
4253 Fun = FunctionTemplate;
Mike Stump11289f42009-09-09 15:08:12 +00004254
Douglas Gregorcd695e52008-11-10 20:40:00 +00004255 // Look through all of the overloaded functions, searching for one
4256 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004257 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004258 bool FoundNonTemplateFunction = false;
Douglas Gregor9b146582009-07-08 20:55:45 +00004259 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004260 // C++ [over.over]p3:
4261 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00004262 // targets of type "pointer-to-function" or "reference-to-function."
4263 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004264 // type "pointer-to-member-function."
4265 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004266
Mike Stump11289f42009-09-09 15:08:12 +00004267 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregor9b146582009-07-08 20:55:45 +00004268 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Mike Stump11289f42009-09-09 15:08:12 +00004269 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004270 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004271 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004272 // static when converting to member pointer.
4273 if (Method->isStatic() == IsMember)
4274 continue;
4275 } else if (IsMember)
4276 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004277
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004278 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004279 // If the name is a function template, template argument deduction is
4280 // done (14.8.2.2), and if the argument deduction succeeds, the
4281 // resulting template argument list is used to generate a single
4282 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004283 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004284 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00004285 FunctionDecl *Specialization = 0;
4286 TemplateDeductionInfo Info(Context);
4287 if (TemplateDeductionResult Result
4288 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
4289 /*FIXME:*/0, /*FIXME:*/0,
4290 FunctionType, Specialization, Info)) {
4291 // FIXME: make a note of the failed deduction for diagnostics.
4292 (void)Result;
4293 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004294 // FIXME: If the match isn't exact, shouldn't we just drop this as
4295 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00004296 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004297 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004298 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004299 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004300 }
4301 }
Mike Stump11289f42009-09-09 15:08:12 +00004302
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004303 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
4304 // Skip non-static functions when converting to pointer, and static
4305 // when converting to member pointer.
4306 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004307 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004308 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004309 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004310
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004311 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004312 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004313 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004314 FoundNonTemplateFunction = true;
4315 }
Mike Stump11289f42009-09-09 15:08:12 +00004316 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004317 }
4318
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004319 // If there were 0 or 1 matches, we're done.
4320 if (Matches.empty())
4321 return 0;
4322 else if (Matches.size() == 1)
4323 return *Matches.begin();
4324
4325 // C++ [over.over]p4:
4326 // If more than one function is selected, [...]
Douglas Gregor05155d82009-08-21 23:19:43 +00004327 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorfae1d712009-09-26 03:56:17 +00004328 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004329 // [...] and any given function template specialization F1 is
4330 // eliminated if the set contains a second function template
4331 // specialization whose function template is more specialized
4332 // than the function template of F1 according to the partial
4333 // ordering rules of 14.5.5.2.
4334
4335 // The algorithm specified above is quadratic. We instead use a
4336 // two-pass algorithm (similar to the one used to identify the
4337 // best viable function in an overload set) that identifies the
4338 // best function template (if it exists).
Douglas Gregorfae1d712009-09-26 03:56:17 +00004339 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
4340 Matches.end());
4341 return getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4342 TPOC_Other, From->getLocStart(),
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004343 PDiag(),
4344 PDiag(diag::err_addr_ovl_ambiguous)
Douglas Gregorfae1d712009-09-26 03:56:17 +00004345 << TemplateMatches[0]->getDeclName(),
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004346 PDiag(diag::err_ovl_template_candidate));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004347 }
Mike Stump11289f42009-09-09 15:08:12 +00004348
Douglas Gregorfae1d712009-09-26 03:56:17 +00004349 // [...] any function template specializations in the set are
4350 // eliminated if the set also contains a non-template function, [...]
4351 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4352 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4353 if ((*M)->getPrimaryTemplate() == 0)
4354 RemainingMatches.push_back(*M);
4355
Mike Stump11289f42009-09-09 15:08:12 +00004356 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004357 // selected function.
4358 if (RemainingMatches.size() == 1)
4359 return RemainingMatches.front();
Mike Stump11289f42009-09-09 15:08:12 +00004360
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004361 // FIXME: We should probably return the same thing that BestViableFunction
4362 // returns (even if we issue the diagnostics here).
4363 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4364 << RemainingMatches[0]->getDeclName();
4365 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4366 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004367 return 0;
4368}
4369
Douglas Gregorcabea402009-09-22 15:41:20 +00004370/// \brief Add a single candidate to the overload set.
4371static void AddOverloadedCallCandidate(Sema &S,
4372 AnyFunctionDecl Callee,
4373 bool &ArgumentDependentLookup,
4374 bool HasExplicitTemplateArgs,
4375 const TemplateArgument *ExplicitTemplateArgs,
4376 unsigned NumExplicitTemplateArgs,
4377 Expr **Args, unsigned NumArgs,
4378 OverloadCandidateSet &CandidateSet,
4379 bool PartialOverloading) {
4380 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
4381 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
4382 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4383 PartialOverloading);
4384
4385 if (Func->getDeclContext()->isRecord() ||
4386 Func->getDeclContext()->isFunctionOrMethod())
4387 ArgumentDependentLookup = false;
4388 return;
4389 }
4390
4391 FunctionTemplateDecl *FuncTemplate = cast<FunctionTemplateDecl>(Callee);
4392 S.AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4393 ExplicitTemplateArgs,
4394 NumExplicitTemplateArgs,
4395 Args, NumArgs, CandidateSet);
4396
4397 if (FuncTemplate->getDeclContext()->isRecord())
4398 ArgumentDependentLookup = false;
4399}
4400
4401/// \brief Add the overload candidates named by callee and/or found by argument
4402/// dependent lookup to the given overload set.
4403void Sema::AddOverloadedCallCandidates(NamedDecl *Callee,
4404 DeclarationName &UnqualifiedName,
4405 bool &ArgumentDependentLookup,
4406 bool HasExplicitTemplateArgs,
4407 const TemplateArgument *ExplicitTemplateArgs,
4408 unsigned NumExplicitTemplateArgs,
4409 Expr **Args, unsigned NumArgs,
4410 OverloadCandidateSet &CandidateSet,
4411 bool PartialOverloading) {
4412 // Add the functions denoted by Callee to the set of candidate
4413 // functions. While we're doing so, track whether argument-dependent
4414 // lookup still applies, per:
4415 //
4416 // C++0x [basic.lookup.argdep]p3:
4417 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4418 // and let Y be the lookup set produced by argument dependent
4419 // lookup (defined as follows). If X contains
4420 //
4421 // -- a declaration of a class member, or
4422 //
4423 // -- a block-scope function declaration that is not a
4424 // using-declaration (FIXME: check for using declaration), or
4425 //
4426 // -- a declaration that is neither a function or a function
4427 // template
4428 //
4429 // then Y is empty.
4430 if (!Callee) {
4431 // Nothing to do.
4432 } else if (OverloadedFunctionDecl *Ovl
4433 = dyn_cast<OverloadedFunctionDecl>(Callee)) {
4434 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4435 FuncEnd = Ovl->function_end();
4436 Func != FuncEnd; ++Func)
4437 AddOverloadedCallCandidate(*this, *Func, ArgumentDependentLookup,
4438 HasExplicitTemplateArgs,
4439 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4440 Args, NumArgs, CandidateSet,
4441 PartialOverloading);
4442 } else if (isa<FunctionDecl>(Callee) || isa<FunctionTemplateDecl>(Callee))
4443 AddOverloadedCallCandidate(*this,
4444 AnyFunctionDecl::getFromNamedDecl(Callee),
4445 ArgumentDependentLookup,
4446 HasExplicitTemplateArgs,
4447 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4448 Args, NumArgs, CandidateSet,
4449 PartialOverloading);
4450 // FIXME: assert isa<FunctionDecl> || isa<FunctionTemplateDecl> rather than
4451 // checking dynamically.
4452
4453 if (Callee)
4454 UnqualifiedName = Callee->getDeclName();
4455
4456 if (ArgumentDependentLookup)
4457 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
4458 HasExplicitTemplateArgs,
4459 ExplicitTemplateArgs,
4460 NumExplicitTemplateArgs,
4461 CandidateSet,
4462 PartialOverloading);
4463}
4464
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004465/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00004466/// (which eventually refers to the declaration Func) and the call
4467/// arguments Args/NumArgs, attempt to resolve the function call down
4468/// to a specific function. If overload resolution succeeds, returns
4469/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00004470/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004471/// arguments and Fn, and returns NULL.
Douglas Gregore254f902009-02-04 00:32:51 +00004472FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004473 DeclarationName UnqualifiedName,
Douglas Gregor89026b52009-06-30 23:57:56 +00004474 bool HasExplicitTemplateArgs,
4475 const TemplateArgument *ExplicitTemplateArgs,
4476 unsigned NumExplicitTemplateArgs,
Douglas Gregora60a6912008-11-26 06:01:48 +00004477 SourceLocation LParenLoc,
4478 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004479 SourceLocation *CommaLocs,
Douglas Gregore254f902009-02-04 00:32:51 +00004480 SourceLocation RParenLoc,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004481 bool &ArgumentDependentLookup) {
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004482 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004483
4484 // Add the functions denoted by Callee to the set of candidate
Douglas Gregorcabea402009-09-22 15:41:20 +00004485 // functions.
4486 AddOverloadedCallCandidates(Callee, UnqualifiedName, ArgumentDependentLookup,
4487 HasExplicitTemplateArgs, ExplicitTemplateArgs,
4488 NumExplicitTemplateArgs, Args, NumArgs,
4489 CandidateSet);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004490 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004491 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregora60a6912008-11-26 06:01:48 +00004492 case OR_Success:
4493 return Best->Function;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004494
4495 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00004496 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004497 diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004498 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004499 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4500 break;
4501
4502 case OR_Ambiguous:
4503 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004504 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004505 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4506 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004507
4508 case OR_Deleted:
4509 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4510 << Best->Function->isDeleted()
4511 << UnqualifiedName
4512 << Fn->getSourceRange();
4513 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4514 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004515 }
4516
4517 // Overload resolution failed. Destroy all of the subexpressions and
4518 // return NULL.
4519 Fn->Destroy(Context);
4520 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4521 Args[Arg]->Destroy(Context);
4522 return 0;
4523}
4524
Douglas Gregor084d8552009-03-13 23:49:33 +00004525/// \brief Create a unary operation that may resolve to an overloaded
4526/// operator.
4527///
4528/// \param OpLoc The location of the operator itself (e.g., '*').
4529///
4530/// \param OpcIn The UnaryOperator::Opcode that describes this
4531/// operator.
4532///
4533/// \param Functions The set of non-member functions that will be
4534/// considered by overload resolution. The caller needs to build this
4535/// set based on the context using, e.g.,
4536/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4537/// set should not contain any member functions; those will be added
4538/// by CreateOverloadedUnaryOp().
4539///
4540/// \param input The input argument.
4541Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4542 unsigned OpcIn,
4543 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00004544 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004545 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4546 Expr *Input = (Expr *)input.get();
4547
4548 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4549 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4550 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4551
4552 Expr *Args[2] = { Input, 0 };
4553 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004554
Douglas Gregor084d8552009-03-13 23:49:33 +00004555 // For post-increment and post-decrement, add the implicit '0' as
4556 // the second argument, so that we know this is a post-increment or
4557 // post-decrement.
4558 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4559 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00004560 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00004561 SourceLocation());
4562 NumArgs = 2;
4563 }
4564
4565 if (Input->isTypeDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00004566 OverloadedFunctionDecl *Overloads
Douglas Gregor084d8552009-03-13 23:49:33 +00004567 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004568 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00004569 FuncEnd = Functions.end();
4570 Func != FuncEnd; ++Func)
4571 Overloads->addOverload(*Func);
4572
4573 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4574 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004575
Douglas Gregor084d8552009-03-13 23:49:33 +00004576 input.release();
4577 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4578 &Args[0], NumArgs,
4579 Context.DependentTy,
4580 OpLoc));
4581 }
4582
4583 // Build an empty overload set.
4584 OverloadCandidateSet CandidateSet;
4585
4586 // Add the candidates from the given function set.
4587 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4588
4589 // Add operator candidates that are member functions.
4590 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4591
4592 // Add builtin operator candidates.
4593 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4594
4595 // Perform overload resolution.
4596 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004597 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004598 case OR_Success: {
4599 // We found a built-in operator or an overloaded operator.
4600 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00004601
Douglas Gregor084d8552009-03-13 23:49:33 +00004602 if (FnDecl) {
4603 // We matched an overloaded operator. Build a call to that
4604 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00004605
Douglas Gregor084d8552009-03-13 23:49:33 +00004606 // Convert the arguments.
4607 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4608 if (PerformObjectArgumentInitialization(Input, Method))
4609 return ExprError();
4610 } else {
4611 // Convert the arguments.
4612 if (PerformCopyInitialization(Input,
4613 FnDecl->getParamDecl(0)->getType(),
4614 "passing"))
4615 return ExprError();
4616 }
4617
4618 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004619 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004620
Douglas Gregor084d8552009-03-13 23:49:33 +00004621 // Build the actual expression node.
4622 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4623 SourceLocation());
4624 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004625
Douglas Gregor084d8552009-03-13 23:49:33 +00004626 input.release();
Mike Stump11289f42009-09-09 15:08:12 +00004627
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004628 ExprOwningPtr<CallExpr> TheCall(this,
4629 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4630 &Input, 1, ResultTy, OpLoc));
4631
4632 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4633 FnDecl))
4634 return ExprError();
4635
4636 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00004637 } else {
4638 // We matched a built-in operator. Convert the arguments, then
4639 // break out so that we will build the appropriate built-in
4640 // operator node.
4641 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4642 Best->Conversions[0], "passing"))
4643 return ExprError();
4644
4645 break;
4646 }
4647 }
4648
4649 case OR_No_Viable_Function:
4650 // No viable function; fall through to handling this as a
4651 // built-in operator, which will produce an error message for us.
4652 break;
4653
4654 case OR_Ambiguous:
4655 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4656 << UnaryOperator::getOpcodeStr(Opc)
4657 << Input->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004658 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4659 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00004660 return ExprError();
4661
4662 case OR_Deleted:
4663 Diag(OpLoc, diag::err_ovl_deleted_oper)
4664 << Best->Function->isDeleted()
4665 << UnaryOperator::getOpcodeStr(Opc)
4666 << Input->getSourceRange();
4667 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4668 return ExprError();
4669 }
4670
4671 // Either we found no viable overloaded operator or we matched a
4672 // built-in operator. In either case, fall through to trying to
4673 // build a built-in operation.
4674 input.release();
4675 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4676}
4677
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004678/// \brief Create a binary operation that may resolve to an overloaded
4679/// operator.
4680///
4681/// \param OpLoc The location of the operator itself (e.g., '+').
4682///
4683/// \param OpcIn The BinaryOperator::Opcode that describes this
4684/// operator.
4685///
4686/// \param Functions The set of non-member functions that will be
4687/// considered by overload resolution. The caller needs to build this
4688/// set based on the context using, e.g.,
4689/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4690/// set should not contain any member functions; those will be added
4691/// by CreateOverloadedBinOp().
4692///
4693/// \param LHS Left-hand argument.
4694/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00004695Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004696Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004697 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004698 FunctionSet &Functions,
4699 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004700 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00004701 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004702
4703 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4704 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4705 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4706
4707 // If either side is type-dependent, create an appropriate dependent
4708 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00004709 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004710 // .* cannot be overloaded.
4711 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004712 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004713 Context.DependentTy, OpLoc));
4714
Mike Stump11289f42009-09-09 15:08:12 +00004715 OverloadedFunctionDecl *Overloads
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004716 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004717 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004718 FuncEnd = Functions.end();
4719 Func != FuncEnd; ++Func)
4720 Overloads->addOverload(*Func);
4721
4722 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4723 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004724
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004725 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00004726 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004727 Context.DependentTy,
4728 OpLoc));
4729 }
4730
4731 // If this is the .* operator, which is not overloadable, just
4732 // create a built-in binary operator.
4733 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004734 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004735
4736 // If this is one of the assignment operators, we only perform
4737 // overload resolution if the left-hand side is a class or
4738 // enumeration type (C++ [expr.ass]p3).
4739 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregore9899d92009-08-26 17:08:25 +00004740 !Args[0]->getType()->isOverloadableType())
4741 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004742
Douglas Gregor084d8552009-03-13 23:49:33 +00004743 // Build an empty overload set.
4744 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004745
4746 // Add the candidates from the given function set.
4747 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4748
4749 // Add operator candidates that are member functions.
4750 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4751
4752 // Add builtin operator candidates.
4753 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4754
4755 // Perform overload resolution.
4756 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004757 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004758 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004759 // We found a built-in operator or an overloaded operator.
4760 FunctionDecl *FnDecl = Best->Function;
4761
4762 if (FnDecl) {
4763 // We matched an overloaded operator. Build a call to that
4764 // operator.
4765
4766 // Convert the arguments.
4767 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregore9899d92009-08-26 17:08:25 +00004768 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4769 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004770 "passing"))
4771 return ExprError();
4772 } else {
4773 // Convert the arguments.
Douglas Gregore9899d92009-08-26 17:08:25 +00004774 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004775 "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004776 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004777 "passing"))
4778 return ExprError();
4779 }
4780
4781 // Determine the result type
4782 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00004783 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004784 ResultTy = ResultTy.getNonReferenceType();
4785
4786 // Build the actual expression node.
4787 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00004788 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004789 UsualUnaryConversions(FnExpr);
4790
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00004791 ExprOwningPtr<CXXOperatorCallExpr>
4792 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4793 Args, 2, ResultTy,
4794 OpLoc));
4795
4796 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4797 FnDecl))
4798 return ExprError();
4799
4800 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004801 } else {
4802 // We matched a built-in operator. Convert the arguments, then
4803 // break out so that we will build the appropriate built-in
4804 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00004805 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004806 Best->Conversions[0], "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004807 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004808 Best->Conversions[1], "passing"))
4809 return ExprError();
4810
4811 break;
4812 }
4813 }
4814
Douglas Gregor66950a32009-09-30 21:46:01 +00004815 case OR_No_Viable_Function: {
4816 // C++ [over.match.oper]p9:
4817 // If the operator is the operator , [...] and there are no
4818 // viable functions, then the operator is assumed to be the
4819 // built-in operator and interpreted according to clause 5.
4820 if (Opc == BinaryOperator::Comma)
4821 break;
4822
Sebastian Redl027de2a2009-05-21 11:50:50 +00004823 // For class as left operand for assignment or compound assigment operator
4824 // do not fall through to handling in built-in, but report that no overloaded
4825 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00004826 OwningExprResult Result = ExprError();
4827 if (Args[0]->getType()->isRecordType() &&
4828 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00004829 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4830 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004831 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00004832 } else {
4833 // No viable function; try to create a built-in operation, which will
4834 // produce an error. Then, show the non-viable candidates.
4835 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00004836 }
Douglas Gregor66950a32009-09-30 21:46:01 +00004837 assert(Result.isInvalid() &&
4838 "C++ binary operator overloading is missing candidates!");
4839 if (Result.isInvalid())
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004840 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
4841 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00004842 return move(Result);
4843 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004844
4845 case OR_Ambiguous:
4846 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4847 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004848 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004849 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4850 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004851 return ExprError();
4852
4853 case OR_Deleted:
4854 Diag(OpLoc, diag::err_ovl_deleted_oper)
4855 << Best->Function->isDeleted()
4856 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004857 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004858 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4859 return ExprError();
4860 }
4861
Douglas Gregor66950a32009-09-30 21:46:01 +00004862 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00004863 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004864}
4865
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004866/// BuildCallToMemberFunction - Build a call to a member
4867/// function. MemExpr is the expression that refers to the member
4868/// function (and includes the object parameter), Args/NumArgs are the
4869/// arguments to the function call (not including the object
4870/// parameter). The caller needs to validate that the member
4871/// expression refers to a member function or an overloaded member
4872/// function.
4873Sema::ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00004874Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4875 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004876 unsigned NumArgs, SourceLocation *CommaLocs,
4877 SourceLocation RParenLoc) {
4878 // Dig out the member expression. This holds both the object
4879 // argument and the member function we're referring to.
4880 MemberExpr *MemExpr = 0;
4881 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4882 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4883 else
4884 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4885 assert(MemExpr && "Building member call without member expression");
4886
4887 // Extract the object argument.
4888 Expr *ObjectArg = MemExpr->getBase();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004889
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004890 CXXMethodDecl *Method = 0;
Douglas Gregor97628d62009-08-21 00:16:32 +00004891 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4892 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004893 // Add overload candidates
4894 OverloadCandidateSet CandidateSet;
Douglas Gregor97628d62009-08-21 00:16:32 +00004895 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004896
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004897 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4898 Func != FuncEnd; ++Func) {
4899 if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
Mike Stump11289f42009-09-09 15:08:12 +00004900 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004901 /*SuppressUserConversions=*/false);
4902 else
Douglas Gregor84f14dd2009-09-01 00:37:14 +00004903 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4904 MemExpr->hasExplicitTemplateArgumentList(),
4905 MemExpr->getTemplateArgs(),
4906 MemExpr->getNumTemplateArgs(),
4907 ObjectArg, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004908 CandidateSet,
4909 /*SuppressUsedConversions=*/false);
4910 }
Mike Stump11289f42009-09-09 15:08:12 +00004911
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004912 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004913 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004914 case OR_Success:
4915 Method = cast<CXXMethodDecl>(Best->Function);
4916 break;
4917
4918 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00004919 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004920 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00004921 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004922 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4923 // FIXME: Leaking incoming expressions!
4924 return true;
4925
4926 case OR_Ambiguous:
Mike Stump11289f42009-09-09 15:08:12 +00004927 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004928 diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00004929 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004930 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4931 // FIXME: Leaking incoming expressions!
4932 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004933
4934 case OR_Deleted:
Mike Stump11289f42009-09-09 15:08:12 +00004935 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00004936 diag::err_ovl_deleted_member_call)
4937 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00004938 << DeclName << MemExprE->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00004939 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4940 // FIXME: Leaking incoming expressions!
4941 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004942 }
4943
4944 FixOverloadedFunctionReference(MemExpr, Method);
4945 } else {
4946 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4947 }
4948
4949 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00004950 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004951 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
Mike Stump11289f42009-09-09 15:08:12 +00004952 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004953 Method->getResultType().getNonReferenceType(),
4954 RParenLoc));
4955
Anders Carlssonc4859ba2009-10-10 00:06:20 +00004956 // Check for a valid return type.
4957 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
4958 TheCall.get(), Method))
4959 return true;
4960
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004961 // Convert the object argument (for a non-static member function call).
Mike Stump11289f42009-09-09 15:08:12 +00004962 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004963 PerformObjectArgumentInitialization(ObjectArg, Method))
4964 return true;
4965 MemExpr->setBase(ObjectArg);
4966
4967 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004968 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004969 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004970 RParenLoc))
4971 return true;
4972
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004973 if (CheckFunctionCall(Method, TheCall.get()))
4974 return true;
Anders Carlsson8c84c202009-08-16 03:42:12 +00004975
4976 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004977}
4978
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004979/// BuildCallToObjectOfClassType - Build a call to an object of class
4980/// type (C++ [over.call.object]), which can end up invoking an
4981/// overloaded function call operator (@c operator()) or performing a
4982/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00004983Sema::ExprResult
4984Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00004985 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004986 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004987 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004988 SourceLocation RParenLoc) {
4989 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004990 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00004991
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004992 // C++ [over.call.object]p1:
4993 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00004994 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004995 // candidate functions includes at least the function call
4996 // operators of T. The function call operators of T are obtained by
4997 // ordinary lookup of the name operator() in the context of
4998 // (E).operator().
4999 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00005000 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor55297ac2008-12-23 00:26:44 +00005001 DeclContext::lookup_const_iterator Oper, OperEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005002 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor55297ac2008-12-23 00:26:44 +00005003 Oper != OperEnd; ++Oper)
Mike Stump11289f42009-09-09 15:08:12 +00005004 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
Douglas Gregor55297ac2008-12-23 00:26:44 +00005005 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005006
Douglas Gregorab7897a2008-11-19 22:57:39 +00005007 // C++ [over.call.object]p2:
5008 // In addition, for each conversion function declared in T of the
5009 // form
5010 //
5011 // operator conversion-type-id () cv-qualifier;
5012 //
5013 // where cv-qualifier is the same cv-qualification as, or a
5014 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00005015 // denotes the type "pointer to function of (P1,...,Pn) returning
5016 // R", or the type "reference to pointer to function of
5017 // (P1,...,Pn) returning R", or the type "reference to function
5018 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00005019 // is also considered as a candidate function. Similarly,
5020 // surrogate call functions are added to the set of candidate
5021 // functions for each conversion function declared in an
5022 // accessible base class provided the function is not hidden
5023 // within T by another intervening declaration.
Mike Stump11289f42009-09-09 15:08:12 +00005024
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005025 if (!RequireCompleteType(SourceLocation(), Object->getType(), 0)) {
5026 // FIXME: Look in base classes for more conversion operators!
Mike Stump11289f42009-09-09 15:08:12 +00005027 OverloadedFunctionDecl *Conversions
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005028 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00005029 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005030 Func = Conversions->function_begin(),
5031 FuncEnd = Conversions->function_end();
5032 Func != FuncEnd; ++Func) {
5033 CXXConversionDecl *Conv;
5034 FunctionTemplateDecl *ConvTemplate;
5035 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Douglas Gregor05155d82009-08-21 23:19:43 +00005036
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005037 // Skip over templated conversion functions; they aren't
5038 // surrogates.
5039 if (ConvTemplate)
5040 continue;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005041
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005042 // Strip the reference type (if any) and then the pointer type (if
5043 // any) to get down to what might be a function type.
5044 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5045 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5046 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005047
John McCall9dd450b2009-09-21 23:43:11 +00005048 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005049 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
5050 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00005051 }
Mike Stump11289f42009-09-09 15:08:12 +00005052
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005053 // Perform overload resolution.
5054 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005055 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005056 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00005057 // Overload resolution succeeded; we'll build the appropriate call
5058 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005059 break;
5060
5061 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00005062 Diag(Object->getSourceRange().getBegin(),
Sebastian Redl15b02d22008-11-22 13:44:36 +00005063 diag::err_ovl_no_viable_object_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00005064 << Object->getType() << Object->getSourceRange();
Sebastian Redl15b02d22008-11-22 13:44:36 +00005065 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005066 break;
5067
5068 case OR_Ambiguous:
5069 Diag(Object->getSourceRange().getBegin(),
5070 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005071 << Object->getType() << Object->getSourceRange();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005072 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5073 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005074
5075 case OR_Deleted:
5076 Diag(Object->getSourceRange().getBegin(),
5077 diag::err_ovl_deleted_object_call)
5078 << Best->Function->isDeleted()
5079 << Object->getType() << Object->getSourceRange();
5080 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5081 break;
Mike Stump11289f42009-09-09 15:08:12 +00005082 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005083
Douglas Gregorab7897a2008-11-19 22:57:39 +00005084 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005085 // We had an error; delete all of the subexpressions and return
5086 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00005087 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005088 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00005089 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005090 return true;
5091 }
5092
Douglas Gregorab7897a2008-11-19 22:57:39 +00005093 if (Best->Function == 0) {
5094 // Since there is no function declaration, this is one of the
5095 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00005096 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00005097 = cast<CXXConversionDecl>(
5098 Best->Conversions[0].UserDefined.ConversionFunction);
5099
5100 // We selected one of the surrogate functions that converts the
5101 // object parameter to a function pointer. Perform the conversion
5102 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005103
5104 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005105 // and then call it.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005106 CXXMemberCallExpr *CE =
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005107 BuildCXXMemberCallExpr(Object, Conv);
5108
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005109 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005110 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5111 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005112 }
5113
5114 // We found an overloaded operator(). Build a CXXOperatorCallExpr
5115 // that calls this method, using Object for the implicit object
5116 // parameter and passing along the remaining arguments.
5117 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00005118 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005119
5120 unsigned NumArgsInProto = Proto->getNumArgs();
5121 unsigned NumArgsToCheck = NumArgs;
5122
5123 // Build the full argument list for the method call (the
5124 // implicit object parameter is placed at the beginning of the
5125 // list).
5126 Expr **MethodArgs;
5127 if (NumArgs < NumArgsInProto) {
5128 NumArgsToCheck = NumArgsInProto;
5129 MethodArgs = new Expr*[NumArgsInProto + 1];
5130 } else {
5131 MethodArgs = new Expr*[NumArgs + 1];
5132 }
5133 MethodArgs[0] = Object;
5134 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5135 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00005136
5137 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00005138 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005139 UsualUnaryConversions(NewFn);
5140
5141 // Once we've built TheCall, all of the expressions are properly
5142 // owned.
5143 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005144 ExprOwningPtr<CXXOperatorCallExpr>
5145 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005146 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00005147 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005148 delete [] MethodArgs;
5149
Anders Carlsson3d5829c2009-10-13 21:49:31 +00005150 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5151 Method))
5152 return true;
5153
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005154 // We may have default arguments. If so, we need to allocate more
5155 // slots in the call for them.
5156 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00005157 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005158 else if (NumArgs > NumArgsInProto)
5159 NumArgsToCheck = NumArgsInProto;
5160
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005161 bool IsError = false;
5162
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005163 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005164 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005165 TheCall->setArg(0, Object);
5166
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005167
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005168 // Check the argument types.
5169 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005170 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005171 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005172 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00005173
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005174 // Pass the argument.
5175 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005176 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005177 } else {
Anders Carlssone8271232009-08-14 18:30:22 +00005178 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005179 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005180
5181 TheCall->setArg(i + 1, Arg);
5182 }
5183
5184 // If this is a variadic call, handle args passed through "...".
5185 if (Proto->isVariadic()) {
5186 // Promote the arguments (C99 6.5.2.2p7).
5187 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5188 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005189 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005190 TheCall->setArg(i + 1, Arg);
5191 }
5192 }
5193
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005194 if (IsError) return true;
5195
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005196 if (CheckFunctionCall(Method, TheCall.get()))
5197 return true;
5198
Anders Carlsson1c83deb2009-08-16 03:53:54 +00005199 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005200}
5201
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005202/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00005203/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005204/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00005205Sema::OwningExprResult
5206Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5207 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005208 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00005209
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005210 // C++ [over.ref]p1:
5211 //
5212 // [...] An expression x->m is interpreted as (x.operator->())->m
5213 // for a class object x of type T if T::operator->() exists and if
5214 // the operator is selected as the best match function by the
5215 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005216 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5217 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005218 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00005219
John McCall9f3059a2009-10-09 21:13:30 +00005220 LookupResult R;
5221 LookupQualifiedName(R, BaseRecord->getDecl(), OpName, LookupOrdinaryName);
Anders Carlsson78b54932009-09-10 23:18:36 +00005222
5223 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
5224 Oper != OperEnd; ++Oper)
Douglas Gregor55297ac2008-12-23 00:26:44 +00005225 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005226 /*SuppressUserConversions=*/false);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005227
5228 // Perform overload resolution.
5229 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005230 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005231 case OR_Success:
5232 // Overload resolution succeeded; we'll build the call below.
5233 break;
5234
5235 case OR_No_Viable_Function:
5236 if (CandidateSet.empty())
5237 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00005238 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005239 else
5240 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00005241 << "operator->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005242 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregord8061562009-08-06 03:17:00 +00005243 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005244
5245 case OR_Ambiguous:
5246 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00005247 << "->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005248 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005249 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005250
5251 case OR_Deleted:
5252 Diag(OpLoc, diag::err_ovl_deleted_oper)
5253 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00005254 << "->" << Base->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005255 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005256 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005257 }
5258
5259 // Convert the object parameter.
5260 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00005261 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00005262 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00005263
5264 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00005265 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005266
5267 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00005268 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5269 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005270 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005271
5272 QualType ResultTy = Method->getResultType().getNonReferenceType();
5273 ExprOwningPtr<CXXOperatorCallExpr>
5274 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
5275 &Base, 1, ResultTy, OpLoc));
5276
5277 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
5278 Method))
5279 return ExprError();
5280 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005281}
5282
Douglas Gregorcd695e52008-11-10 20:40:00 +00005283/// FixOverloadedFunctionReference - E is an expression that refers to
5284/// a C++ overloaded function (possibly with some parentheses and
5285/// perhaps a '&' around it). We have resolved the overloaded function
5286/// to the function declaration Fn, so patch up the expression E to
5287/// refer (possibly indirectly) to Fn.
5288void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
5289 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5290 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5291 E->setType(PE->getSubExpr()->getType());
5292 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00005293 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00005294 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005295 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5296 if (Method->isStatic()) {
5297 // Do nothing: static member functions aren't any different
5298 // from non-member functions.
Mike Stump11289f42009-09-09 15:08:12 +00005299 } else if (QualifiedDeclRefExpr *DRE
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005300 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
5301 // We have taken the address of a pointer to member
5302 // function. Perform the computation here so that we get the
5303 // appropriate pointer to member type.
5304 DRE->setDecl(Fn);
5305 DRE->setType(Fn->getType());
5306 QualType ClassType
5307 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
Mike Stump11289f42009-09-09 15:08:12 +00005308 E->setType(Context.getMemberPointerType(Fn->getType(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005309 ClassType.getTypePtr()));
5310 return;
5311 }
5312 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005313 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005314 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregorcd695e52008-11-10 20:40:00 +00005315 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor9b146582009-07-08 20:55:45 +00005316 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
Mike Stump11289f42009-09-09 15:08:12 +00005317 isa<FunctionTemplateDecl>(DR->getDecl())) &&
Douglas Gregor9b146582009-07-08 20:55:45 +00005318 "Expected overloaded function or function template");
Douglas Gregorcd695e52008-11-10 20:40:00 +00005319 DR->setDecl(Fn);
5320 E->setType(Fn->getType());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005321 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
5322 MemExpr->setMemberDecl(Fn);
5323 E->setType(Fn->getType());
Douglas Gregorcd695e52008-11-10 20:40:00 +00005324 } else {
5325 assert(false && "Invalid reference to overloaded function");
5326 }
5327}
5328
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005329} // end namespace clang