blob: 7366ec978b4a0fa7d632aaa890525146404a3dd7 [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000020#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000022#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000024#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000025#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000026#include "llvm/Support/Compiler.h"
27#include <algorithm>
Torok Edwindb714922009-08-24 13:25:12 +000028#include <cstdio>
Douglas Gregor5251f1b2008-10-21 16:13:35 +000029
30namespace clang {
31
32/// GetConversionCategory - Retrieve the implicit conversion
33/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000034ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000035GetConversionCategory(ImplicitConversionKind Kind) {
36 static const ImplicitConversionCategory
37 Category[(int)ICK_Num_Conversion_Kinds] = {
38 ICC_Identity,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
41 ICC_Lvalue_Transformation,
42 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000055 ICC_Conversion
56 };
57 return Category[(int)Kind];
58}
59
60/// GetConversionRank - Retrieve the implicit conversion rank
61/// corresponding to the given implicit conversion kind.
62ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
63 static const ImplicitConversionRank
64 Rank[(int)ICK_Num_Conversion_Kinds] = {
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
70 ICR_Promotion,
71 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000072 ICR_Promotion,
73 ICR_Conversion,
74 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000075 ICR_Conversion,
76 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000080 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000081 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000082 ICR_Conversion
83 };
84 return Rank[(int)Kind];
85}
86
87/// GetImplicitConversionName - Return the name of this kind of
88/// implicit conversion.
89const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
90 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
91 "No conversion",
92 "Lvalue-to-rvalue",
93 "Array-to-pointer",
94 "Function-to-pointer",
95 "Qualification",
96 "Integral promotion",
97 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +000098 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +000099 "Integral conversion",
100 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000101 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000102 "Floating-integral conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000103 "Complex-real conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000104 "Pointer conversion",
105 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000106 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000107 "Compatible-types conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000108 "Derived-to-base conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000109 };
110 return Name[Kind];
111}
112
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000113/// StandardConversionSequence - Set the standard conversion
114/// sequence to the identity conversion.
115void StandardConversionSequence::setAsIdentityConversion() {
116 First = ICK_Identity;
117 Second = ICK_Identity;
118 Third = ICK_Identity;
119 Deprecated = false;
120 ReferenceBinding = false;
121 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000122 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000123 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000124}
125
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000126/// getRank - Retrieve the rank of this standard conversion sequence
127/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
128/// implicit conversions.
129ImplicitConversionRank StandardConversionSequence::getRank() const {
130 ImplicitConversionRank Rank = ICR_Exact_Match;
131 if (GetConversionRank(First) > Rank)
132 Rank = GetConversionRank(First);
133 if (GetConversionRank(Second) > Rank)
134 Rank = GetConversionRank(Second);
135 if (GetConversionRank(Third) > Rank)
136 Rank = GetConversionRank(Third);
137 return Rank;
138}
139
140/// isPointerConversionToBool - Determines whether this conversion is
141/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000142/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000143/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000144bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000145 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
146 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
147
148 // Note that FromType has not necessarily been transformed by the
149 // array-to-pointer or function-to-pointer implicit conversions, so
150 // check for their presence as well as checking whether FromType is
151 // a pointer.
152 if (ToType->isBooleanType() &&
Douglas Gregor033f56d2008-12-23 00:53:59 +0000153 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000154 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
155 return true;
156
157 return false;
158}
159
Douglas Gregor5c407d92008-10-23 00:40:37 +0000160/// isPointerConversionToVoidPointer - Determines whether this
161/// conversion is a conversion of a pointer to a void pointer. This is
162/// used as part of the ranking of standard conversion sequences (C++
163/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000164bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000165StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000166isPointerConversionToVoidPointer(ASTContext& Context) const {
Douglas Gregor5c407d92008-10-23 00:40:37 +0000167 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
168 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
169
170 // Note that FromType has not necessarily been transformed by the
171 // array-to-pointer implicit conversion, so check for its presence
172 // and redo the conversion to get a pointer.
173 if (First == ICK_Array_To_Pointer)
174 FromType = Context.getArrayDecayedType(FromType);
175
176 if (Second == ICK_Pointer_Conversion)
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000177 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000178 return ToPtrType->getPointeeType()->isVoidType();
179
180 return false;
181}
182
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000183/// DebugPrint - Print this standard conversion sequence to standard
184/// error. Useful for debugging overloading issues.
185void StandardConversionSequence::DebugPrint() const {
186 bool PrintedSomething = false;
187 if (First != ICK_Identity) {
188 fprintf(stderr, "%s", GetImplicitConversionName(First));
189 PrintedSomething = true;
190 }
191
192 if (Second != ICK_Identity) {
193 if (PrintedSomething) {
194 fprintf(stderr, " -> ");
195 }
196 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor2fe98832008-11-03 19:09:14 +0000197
198 if (CopyConstructor) {
199 fprintf(stderr, " (by copy constructor)");
200 } else if (DirectBinding) {
201 fprintf(stderr, " (direct reference binding)");
202 } else if (ReferenceBinding) {
203 fprintf(stderr, " (reference binding)");
204 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205 PrintedSomething = true;
206 }
207
208 if (Third != ICK_Identity) {
209 if (PrintedSomething) {
210 fprintf(stderr, " -> ");
211 }
212 fprintf(stderr, "%s", GetImplicitConversionName(Third));
213 PrintedSomething = true;
214 }
215
216 if (!PrintedSomething) {
217 fprintf(stderr, "No conversions required");
218 }
219}
220
221/// DebugPrint - Print this user-defined conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void UserDefinedConversionSequence::DebugPrint() const {
224 if (Before.First || Before.Second || Before.Third) {
225 Before.DebugPrint();
226 fprintf(stderr, " -> ");
227 }
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000228 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000229 if (After.First || After.Second || After.Third) {
230 fprintf(stderr, " -> ");
231 After.DebugPrint();
232 }
233}
234
235/// DebugPrint - Print this implicit conversion sequence to standard
236/// error. Useful for debugging overloading issues.
237void ImplicitConversionSequence::DebugPrint() const {
238 switch (ConversionKind) {
239 case StandardConversion:
240 fprintf(stderr, "Standard conversion: ");
241 Standard.DebugPrint();
242 break;
243 case UserDefinedConversion:
244 fprintf(stderr, "User-defined conversion: ");
245 UserDefined.DebugPrint();
246 break;
247 case EllipsisConversion:
248 fprintf(stderr, "Ellipsis conversion");
249 break;
250 case BadConversion:
251 fprintf(stderr, "Bad conversion");
252 break;
253 }
254
255 fprintf(stderr, "\n");
256}
257
258// IsOverload - Determine whether the given New declaration is an
259// overload of the Old declaration. This routine returns false if New
260// and Old cannot be overloaded, e.g., if they are functions with the
261// same signature (C++ 1.3.10) or if the Old declaration isn't a
262// function (or overload set). When it does return false and Old is an
263// OverloadedFunctionDecl, MatchedDecl will be set to point to the
Mike Stump11289f42009-09-09 15:08:12 +0000264// FunctionDecl that New cannot be overloaded with.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000265//
266// Example: Given the following input:
267//
268// void f(int, float); // #1
269// void f(int, int); // #2
270// int f(int, int); // #3
271//
272// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000273// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000274//
275// When we process #2, Old is a FunctionDecl for #1. By comparing the
276// parameter types, we see that #1 and #2 are overloaded (since they
277// have different signatures), so this routine returns false;
278// MatchedDecl is unchanged.
279//
280// When we process #3, Old is an OverloadedFunctionDecl containing #1
281// and #2. We compare the signatures of #3 to #1 (they're overloaded,
282// so we do nothing) and then #3 to #2. Since the signatures of #3 and
283// #2 are identical (return types of functions are not part of the
284// signature), IsOverload returns false and MatchedDecl will be set to
285// point to the FunctionDecl for #2.
286bool
John McCall1f82f242009-11-18 22:49:29 +0000287Sema::IsOverload(FunctionDecl *New, LookupResult &Previous, NamedDecl *&Match) {
288 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
289 I != E; ++I) {
290 NamedDecl *Old = (*I)->getUnderlyingDecl();
291 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(Old)) {
292 if (!IsOverload(New, OldT->getTemplatedDecl())) {
293 Match = Old;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000294 return false;
295 }
John McCall1f82f242009-11-18 22:49:29 +0000296 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(Old)) {
297 if (!IsOverload(New, OldF)) {
298 Match = Old;
299 return false;
300 }
301 } else {
302 // (C++ 13p1):
303 // Only function declarations can be overloaded; object and type
304 // declarations cannot be overloaded.
305 Match = Old;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000306 return false;
John McCall1f82f242009-11-18 22:49:29 +0000307 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000308 }
John McCall1f82f242009-11-18 22:49:29 +0000309
310 return true;
311}
312
313bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
314 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
315 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
316
317 // C++ [temp.fct]p2:
318 // A function template can be overloaded with other function templates
319 // and with normal (non-template) functions.
320 if ((OldTemplate == 0) != (NewTemplate == 0))
321 return true;
322
323 // Is the function New an overload of the function Old?
324 QualType OldQType = Context.getCanonicalType(Old->getType());
325 QualType NewQType = Context.getCanonicalType(New->getType());
326
327 // Compare the signatures (C++ 1.3.10) of the two functions to
328 // determine whether they are overloads. If we find any mismatch
329 // in the signature, they are overloads.
330
331 // If either of these functions is a K&R-style function (no
332 // prototype), then we consider them to have matching signatures.
333 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
334 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
335 return false;
336
337 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
338 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
339
340 // The signature of a function includes the types of its
341 // parameters (C++ 1.3.10), which includes the presence or absence
342 // of the ellipsis; see C++ DR 357).
343 if (OldQType != NewQType &&
344 (OldType->getNumArgs() != NewType->getNumArgs() ||
345 OldType->isVariadic() != NewType->isVariadic() ||
346 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
347 NewType->arg_type_begin())))
348 return true;
349
350 // C++ [temp.over.link]p4:
351 // The signature of a function template consists of its function
352 // signature, its return type and its template parameter list. The names
353 // of the template parameters are significant only for establishing the
354 // relationship between the template parameters and the rest of the
355 // signature.
356 //
357 // We check the return type and template parameter lists for function
358 // templates first; the remaining checks follow.
359 if (NewTemplate &&
360 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
361 OldTemplate->getTemplateParameters(),
362 false, TPL_TemplateMatch) ||
363 OldType->getResultType() != NewType->getResultType()))
364 return true;
365
366 // If the function is a class member, its signature includes the
367 // cv-qualifiers (if any) on the function itself.
368 //
369 // As part of this, also check whether one of the member functions
370 // is static, in which case they are not overloads (C++
371 // 13.1p2). While not part of the definition of the signature,
372 // this check is important to determine whether these functions
373 // can be overloaded.
374 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
375 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
376 if (OldMethod && NewMethod &&
377 !OldMethod->isStatic() && !NewMethod->isStatic() &&
378 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
379 return true;
380
381 // The signatures match; this is not an overload.
382 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000383}
384
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000385/// TryImplicitConversion - Attempt to perform an implicit conversion
386/// from the given expression (Expr) to the given type (ToType). This
387/// function returns an implicit conversion sequence that can be used
388/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000389///
390/// void f(float f);
391/// void g(int i) { f(i); }
392///
393/// this routine would produce an implicit conversion sequence to
394/// describe the initialization of f from i, which will be a standard
395/// conversion sequence containing an lvalue-to-rvalue conversion (C++
396/// 4.1) followed by a floating-integral conversion (C++ 4.9).
397//
398/// Note that this routine only determines how the conversion can be
399/// performed; it does not actually perform the conversion. As such,
400/// it will not produce any diagnostics if no conversion is available,
401/// but will instead return an implicit conversion sequence of kind
402/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000403///
404/// If @p SuppressUserConversions, then user-defined conversions are
405/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000406/// If @p AllowExplicit, then explicit user-defined conversions are
407/// permitted.
Sebastian Redl42e92c42009-04-12 17:16:29 +0000408/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
409/// no matter its actual lvalueness.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000410/// If @p UserCast, the implicit conversion is being done for a user-specified
411/// cast.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000412ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000413Sema::TryImplicitConversion(Expr* From, QualType ToType,
414 bool SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +0000415 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000416 bool InOverloadResolution,
417 bool UserCast) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000418 ImplicitConversionSequence ICS;
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000419 OverloadCandidateSet Conversions;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000420 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson228eea32009-08-28 15:33:32 +0000421 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000422 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000423 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000424 (UserDefResult = IsUserDefinedConversion(From, ToType,
425 ICS.UserDefined,
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000426 Conversions,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000427 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000428 ForceRValue, UserCast)) == OR_Success) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000429 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor05379422008-11-03 17:51:48 +0000430 // C++ [over.ics.user]p4:
431 // A conversion of an expression of class type to the same class
432 // type is given Exact Match rank, and a conversion of an
433 // expression of class type to a base class of that type is
434 // given Conversion rank, in spite of the fact that a copy
435 // constructor (i.e., a user-defined conversion function) is
436 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000437 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000438 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000439 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000440 = Context.getCanonicalType(From->getType().getUnqualifiedType());
441 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
442 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000443 // Turn this into a "standard" conversion sequence, so that it
444 // gets ranked with standard conversion sequences.
Douglas Gregor05379422008-11-03 17:51:48 +0000445 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
446 ICS.Standard.setAsIdentityConversion();
447 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
448 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000449 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000450 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000451 ICS.Standard.Second = ICK_Derived_To_Base;
452 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000453 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000454
455 // C++ [over.best.ics]p4:
456 // However, when considering the argument of a user-defined
457 // conversion function that is a candidate by 13.3.1.3 when
458 // invoked for the copying of the temporary in the second step
459 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
460 // 13.3.1.6 in all cases, only standard conversion sequences and
461 // ellipsis conversion sequences are allowed.
462 if (SuppressUserConversions &&
463 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
464 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000465 } else {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000466 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000467 if (UserDefResult == OR_Ambiguous) {
468 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
469 Cand != Conversions.end(); ++Cand)
Fariborz Jahanian574de2c2009-10-12 17:51:19 +0000470 if (Cand->Viable)
471 ICS.ConversionFunctionSet.push_back(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000472 }
473 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000474
475 return ICS;
476}
477
478/// IsStandardConversion - Determines whether there is a standard
479/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
480/// expression From to the type ToType. Standard conversion sequences
481/// only consider non-class types; for conversions that involve class
482/// types, use TryImplicitConversion. If a conversion exists, SCS will
483/// contain the standard conversion sequence required to perform this
484/// conversion and this routine will return true. Otherwise, this
485/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000486bool
487Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000488 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000489 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000490 QualType FromType = From->getType();
491
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000492 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000493 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000494 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000495 SCS.IncompatibleObjC = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000496 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000497 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000498
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000499 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000500 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000501 if (FromType->isRecordType() || ToType->isRecordType()) {
502 if (getLangOptions().CPlusPlus)
503 return false;
504
Mike Stump11289f42009-09-09 15:08:12 +0000505 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000506 }
507
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000508 // The first conversion can be an lvalue-to-rvalue conversion,
509 // array-to-pointer conversion, or function-to-pointer conversion
510 // (C++ 4p1).
511
Mike Stump11289f42009-09-09 15:08:12 +0000512 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000513 // An lvalue (3.10) of a non-function, non-array type T can be
514 // converted to an rvalue.
515 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000516 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000517 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000518 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000519 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000520
521 // If T is a non-class type, the type of the rvalue is the
522 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000523 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
524 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000525 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000526 } else if (FromType->isArrayType()) {
527 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000528 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000529
530 // An lvalue or rvalue of type "array of N T" or "array of unknown
531 // bound of T" can be converted to an rvalue of type "pointer to
532 // T" (C++ 4.2p1).
533 FromType = Context.getArrayDecayedType(FromType);
534
535 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
536 // This conversion is deprecated. (C++ D.4).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000537 SCS.Deprecated = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000538
539 // For the purpose of ranking in overload resolution
540 // (13.3.3.1.1), this conversion is considered an
541 // array-to-pointer conversion followed by a qualification
542 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000543 SCS.Second = ICK_Identity;
544 SCS.Third = ICK_Qualification;
545 SCS.ToTypePtr = ToType.getAsOpaquePtr();
546 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000547 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000548 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
549 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000550 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000551
552 // An lvalue of function type T can be converted to an rvalue of
553 // type "pointer to T." The result is a pointer to the
554 // function. (C++ 4.3p1).
555 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000556 } else if (FunctionDecl *Fn
Douglas Gregorcd695e52008-11-10 20:40:00 +0000557 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000558 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000559 SCS.First = ICK_Function_To_Pointer;
560
561 // We were able to resolve the address of the overloaded function,
562 // so we can convert to the type of that function.
563 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000564 if (ToType->isLValueReferenceType())
565 FromType = Context.getLValueReferenceType(FromType);
566 else if (ToType->isRValueReferenceType())
567 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000568 else if (ToType->isMemberPointerType()) {
569 // Resolve address only succeeds if both sides are member pointers,
570 // but it doesn't have to be the same class. See DR 247.
571 // Note that this means that the type of &Derived::fn can be
572 // Ret (Base::*)(Args) if the fn overload actually found is from the
573 // base class, even if it was brought into the derived class via a
574 // using declaration. The standard isn't clear on this issue at all.
575 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
576 FromType = Context.getMemberPointerType(FromType,
577 Context.getTypeDeclType(M->getParent()).getTypePtr());
578 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000579 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000580 } else {
581 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000582 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000583 }
584
585 // The second conversion can be an integral promotion, floating
586 // point promotion, integral conversion, floating point conversion,
587 // floating-integral conversion, pointer conversion,
588 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000589 // For overloading in C, this can also be a "compatible-type"
590 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000591 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000592 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000593 // The unqualified versions of the types are the same: there's no
594 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000595 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000596 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000597 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000598 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000599 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000600 } else if (IsFloatingPointPromotion(FromType, ToType)) {
601 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000602 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000603 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000604 } else if (IsComplexPromotion(FromType, ToType)) {
605 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000606 SCS.Second = ICK_Complex_Promotion;
607 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000608 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000609 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000610 // Integral conversions (C++ 4.7).
611 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000612 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000613 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000614 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
615 // Floating point conversions (C++ 4.8).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000616 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000617 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000618 } else if (FromType->isComplexType() && ToType->isComplexType()) {
619 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000620 SCS.Second = ICK_Complex_Conversion;
621 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000622 } else if ((FromType->isFloatingType() &&
623 ToType->isIntegralType() && (!ToType->isBooleanType() &&
624 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000625 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000626 ToType->isFloatingType())) {
627 // Floating-integral conversions (C++ 4.9).
628 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000629 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000630 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000631 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
632 (ToType->isComplexType() && FromType->isArithmeticType())) {
633 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000634 SCS.Second = ICK_Complex_Real;
635 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000636 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
637 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000638 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000639 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000640 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000641 } else if (IsMemberPointerConversion(From, FromType, ToType,
642 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000643 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000644 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000645 } else if (ToType->isBooleanType() &&
646 (FromType->isArithmeticType() ||
647 FromType->isEnumeralType() ||
648 FromType->isPointerType() ||
649 FromType->isBlockPointerType() ||
650 FromType->isMemberPointerType() ||
651 FromType->isNullPtrType())) {
652 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000653 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000654 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000655 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000656 Context.typesAreCompatible(ToType, FromType)) {
657 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000658 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000659 } else {
660 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000661 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000662 }
663
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000664 QualType CanonFrom;
665 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000666 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000667 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000668 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000669 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000670 CanonFrom = Context.getCanonicalType(FromType);
671 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000672 } else {
673 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000674 SCS.Third = ICK_Identity;
675
Mike Stump11289f42009-09-09 15:08:12 +0000676 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000677 // [...] Any difference in top-level cv-qualification is
678 // subsumed by the initialization itself and does not constitute
679 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000680 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000681 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000682 if (CanonFrom.getLocalUnqualifiedType()
683 == CanonTo.getLocalUnqualifiedType() &&
684 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000685 FromType = ToType;
686 CanonFrom = CanonTo;
687 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000688 }
689
690 // If we have not converted the argument type to the parameter type,
691 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000692 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000693 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000694
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000695 SCS.ToTypePtr = FromType.getAsOpaquePtr();
696 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000697}
698
699/// IsIntegralPromotion - Determines whether the conversion from the
700/// expression From (whose potentially-adjusted type is FromType) to
701/// ToType is an integral promotion (C++ 4.5). If so, returns true and
702/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000703bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000704 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000705 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000706 if (!To) {
707 return false;
708 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000709
710 // An rvalue of type char, signed char, unsigned char, short int, or
711 // unsigned short int can be converted to an rvalue of type int if
712 // int can represent all the values of the source type; otherwise,
713 // the source rvalue can be converted to an rvalue of type unsigned
714 // int (C++ 4.5p1).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000715 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000716 if (// We can promote any signed, promotable integer type to an int
717 (FromType->isSignedIntegerType() ||
718 // We can promote any unsigned integer type whose size is
719 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000720 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000721 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000722 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000723 }
724
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000725 return To->getKind() == BuiltinType::UInt;
726 }
727
728 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
729 // can be converted to an rvalue of the first of the following types
730 // that can represent all the values of its underlying type: int,
731 // unsigned int, long, or unsigned long (C++ 4.5p2).
732 if ((FromType->isEnumeralType() || FromType->isWideCharType())
733 && ToType->isIntegerType()) {
734 // Determine whether the type we're converting from is signed or
735 // unsigned.
736 bool FromIsSigned;
737 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall9dd450b2009-09-21 23:43:11 +0000738 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000739 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
740 FromIsSigned = UnderlyingType->isSignedIntegerType();
741 } else {
742 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
743 FromIsSigned = true;
744 }
745
746 // The types we'll try to promote to, in the appropriate
747 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000748 QualType PromoteTypes[6] = {
749 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000750 Context.LongTy, Context.UnsignedLongTy ,
751 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000752 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000753 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000754 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
755 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000756 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000757 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
758 // We found the type that we can promote to. If this is the
759 // type we wanted, we have a promotion. Otherwise, no
760 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000761 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000762 }
763 }
764 }
765
766 // An rvalue for an integral bit-field (9.6) can be converted to an
767 // rvalue of type int if int can represent all the values of the
768 // bit-field; otherwise, it can be converted to unsigned int if
769 // unsigned int can represent all the values of the bit-field. If
770 // the bit-field is larger yet, no integral promotion applies to
771 // it. If the bit-field has an enumerated type, it is treated as any
772 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000773 // FIXME: We should delay checking of bit-fields until we actually perform the
774 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000775 using llvm::APSInt;
776 if (From)
777 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000778 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000779 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
780 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
781 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
782 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000783
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000784 // Are we promoting to an int from a bitfield that fits in an int?
785 if (BitWidth < ToSize ||
786 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
787 return To->getKind() == BuiltinType::Int;
788 }
Mike Stump11289f42009-09-09 15:08:12 +0000789
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000790 // Are we promoting to an unsigned int from an unsigned bitfield
791 // that fits into an unsigned int?
792 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
793 return To->getKind() == BuiltinType::UInt;
794 }
Mike Stump11289f42009-09-09 15:08:12 +0000795
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000796 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000797 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000798 }
Mike Stump11289f42009-09-09 15:08:12 +0000799
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000800 // An rvalue of type bool can be converted to an rvalue of type int,
801 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000802 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000803 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000804 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000805
806 return false;
807}
808
809/// IsFloatingPointPromotion - Determines whether the conversion from
810/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
811/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000812bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000813 /// An rvalue of type float can be converted to an rvalue of type
814 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000815 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
816 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000817 if (FromBuiltin->getKind() == BuiltinType::Float &&
818 ToBuiltin->getKind() == BuiltinType::Double)
819 return true;
820
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000821 // C99 6.3.1.5p1:
822 // When a float is promoted to double or long double, or a
823 // double is promoted to long double [...].
824 if (!getLangOptions().CPlusPlus &&
825 (FromBuiltin->getKind() == BuiltinType::Float ||
826 FromBuiltin->getKind() == BuiltinType::Double) &&
827 (ToBuiltin->getKind() == BuiltinType::LongDouble))
828 return true;
829 }
830
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000831 return false;
832}
833
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000834/// \brief Determine if a conversion is a complex promotion.
835///
836/// A complex promotion is defined as a complex -> complex conversion
837/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000838/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000839bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000840 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000841 if (!FromComplex)
842 return false;
843
John McCall9dd450b2009-09-21 23:43:11 +0000844 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000845 if (!ToComplex)
846 return false;
847
848 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000849 ToComplex->getElementType()) ||
850 IsIntegralPromotion(0, FromComplex->getElementType(),
851 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000852}
853
Douglas Gregor237f96c2008-11-26 23:31:11 +0000854/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
855/// the pointer type FromPtr to a pointer to type ToPointee, with the
856/// same type qualifiers as FromPtr has on its pointee type. ToType,
857/// if non-empty, will be a pointer to ToType that may or may not have
858/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000859static QualType
860BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000861 QualType ToPointee, QualType ToType,
862 ASTContext &Context) {
863 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
864 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000865 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000866
867 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000868 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000869 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000870 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000871 return ToType;
872
873 // Build a pointer to ToPointee. It has the right qualifiers
874 // already.
875 return Context.getPointerType(ToPointee);
876 }
877
878 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000879 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000880 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
881 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000882}
883
Mike Stump11289f42009-09-09 15:08:12 +0000884static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000885 bool InOverloadResolution,
886 ASTContext &Context) {
887 // Handle value-dependent integral null pointer constants correctly.
888 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
889 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
890 Expr->getType()->isIntegralType())
891 return !InOverloadResolution;
892
Douglas Gregor56751b52009-09-25 04:25:58 +0000893 return Expr->isNullPointerConstant(Context,
894 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
895 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +0000896}
Mike Stump11289f42009-09-09 15:08:12 +0000897
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000898/// IsPointerConversion - Determines whether the conversion of the
899/// expression From, which has the (possibly adjusted) type FromType,
900/// can be converted to the type ToType via a pointer conversion (C++
901/// 4.10). If so, returns true and places the converted type (that
902/// might differ from ToType in its cv-qualifiers at some level) into
903/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000904///
Douglas Gregora29dc052008-11-27 01:19:21 +0000905/// This routine also supports conversions to and from block pointers
906/// and conversions with Objective-C's 'id', 'id<protocols...>', and
907/// pointers to interfaces. FIXME: Once we've determined the
908/// appropriate overloading rules for Objective-C, we may want to
909/// split the Objective-C checks into a different routine; however,
910/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000911/// conversions, so for now they live here. IncompatibleObjC will be
912/// set if the conversion is an allowed Objective-C conversion that
913/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000914bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000915 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000916 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +0000917 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +0000918 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +0000919 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
920 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000921
Mike Stump11289f42009-09-09 15:08:12 +0000922 // Conversion from a null pointer constant to any Objective-C pointer type.
923 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000924 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +0000925 ConvertedType = ToType;
926 return true;
927 }
928
Douglas Gregor231d1c62008-11-27 00:15:41 +0000929 // Blocks: Block pointers can be converted to void*.
930 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000931 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000932 ConvertedType = ToType;
933 return true;
934 }
935 // Blocks: A null pointer constant can be converted to a block
936 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +0000937 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000938 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000939 ConvertedType = ToType;
940 return true;
941 }
942
Sebastian Redl576fd422009-05-10 18:38:11 +0000943 // If the left-hand-side is nullptr_t, the right side can be a null
944 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000945 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000946 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +0000947 ConvertedType = ToType;
948 return true;
949 }
950
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000951 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000952 if (!ToTypePtr)
953 return false;
954
955 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +0000956 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000957 ConvertedType = ToType;
958 return true;
959 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000960
Douglas Gregor237f96c2008-11-26 23:31:11 +0000961 // Beyond this point, both types need to be pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000962 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +0000963 if (!FromTypePtr)
964 return false;
965
966 QualType FromPointeeType = FromTypePtr->getPointeeType();
967 QualType ToPointeeType = ToTypePtr->getPointeeType();
968
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000969 // An rvalue of type "pointer to cv T," where T is an object type,
970 // can be converted to an rvalue of type "pointer to cv void" (C++
971 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +0000972 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000973 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +0000974 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000975 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000976 return true;
977 }
978
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000979 // When we're overloading in C, we allow a special kind of pointer
980 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +0000981 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000982 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000983 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000984 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +0000985 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000986 return true;
987 }
988
Douglas Gregor5c407d92008-10-23 00:40:37 +0000989 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +0000990 //
Douglas Gregor5c407d92008-10-23 00:40:37 +0000991 // An rvalue of type "pointer to cv D," where D is a class type,
992 // can be converted to an rvalue of type "pointer to cv B," where
993 // B is a base class (clause 10) of D. If B is an inaccessible
994 // (clause 11) or ambiguous (10.2) base class of D, a program that
995 // necessitates this conversion is ill-formed. The result of the
996 // conversion is a pointer to the base class sub-object of the
997 // derived class object. The null pointer value is converted to
998 // the null pointer value of the destination type.
999 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001000 // Note that we do not check for ambiguity or inaccessibility
1001 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001002 if (getLangOptions().CPlusPlus &&
1003 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001004 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001005 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001006 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001007 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001008 ToType, Context);
1009 return true;
1010 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001011
Douglas Gregora119f102008-12-19 19:13:09 +00001012 return false;
1013}
1014
1015/// isObjCPointerConversion - Determines whether this is an
1016/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1017/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001018bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001019 QualType& ConvertedType,
1020 bool &IncompatibleObjC) {
1021 if (!getLangOptions().ObjC1)
1022 return false;
1023
Steve Naroff7cae42b2009-07-10 23:34:53 +00001024 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001025 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001026 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001027 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001028
Steve Naroff7cae42b2009-07-10 23:34:53 +00001029 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001030 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001031 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001032 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001033 ConvertedType = ToType;
1034 return true;
1035 }
1036 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001037 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001038 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001039 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001040 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001041 ConvertedType = ToType;
1042 return true;
1043 }
1044 // Objective C++: We're able to convert from a pointer to an
1045 // interface to a pointer to a different interface.
1046 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1047 ConvertedType = ToType;
1048 return true;
1049 }
1050
1051 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1052 // Okay: this is some kind of implicit downcast of Objective-C
1053 // interfaces, which is permitted. However, we're going to
1054 // complain about it.
1055 IncompatibleObjC = true;
1056 ConvertedType = FromType;
1057 return true;
1058 }
Mike Stump11289f42009-09-09 15:08:12 +00001059 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001060 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001061 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001062 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001063 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001064 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001065 ToPointeeType = ToBlockPtr->getPointeeType();
1066 else
Douglas Gregora119f102008-12-19 19:13:09 +00001067 return false;
1068
Douglas Gregor033f56d2008-12-23 00:53:59 +00001069 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001070 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001071 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001072 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001073 FromPointeeType = FromBlockPtr->getPointeeType();
1074 else
Douglas Gregora119f102008-12-19 19:13:09 +00001075 return false;
1076
Douglas Gregora119f102008-12-19 19:13:09 +00001077 // If we have pointers to pointers, recursively check whether this
1078 // is an Objective-C conversion.
1079 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1080 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1081 IncompatibleObjC)) {
1082 // We always complain about this conversion.
1083 IncompatibleObjC = true;
1084 ConvertedType = ToType;
1085 return true;
1086 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001087 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001088 // differences in the argument and result types are in Objective-C
1089 // pointer conversions. If so, we permit the conversion (but
1090 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001091 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001092 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001093 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001094 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001095 if (FromFunctionType && ToFunctionType) {
1096 // If the function types are exactly the same, this isn't an
1097 // Objective-C pointer conversion.
1098 if (Context.getCanonicalType(FromPointeeType)
1099 == Context.getCanonicalType(ToPointeeType))
1100 return false;
1101
1102 // Perform the quick checks that will tell us whether these
1103 // function types are obviously different.
1104 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1105 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1106 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1107 return false;
1108
1109 bool HasObjCConversion = false;
1110 if (Context.getCanonicalType(FromFunctionType->getResultType())
1111 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1112 // Okay, the types match exactly. Nothing to do.
1113 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1114 ToFunctionType->getResultType(),
1115 ConvertedType, IncompatibleObjC)) {
1116 // Okay, we have an Objective-C pointer conversion.
1117 HasObjCConversion = true;
1118 } else {
1119 // Function types are too different. Abort.
1120 return false;
1121 }
Mike Stump11289f42009-09-09 15:08:12 +00001122
Douglas Gregora119f102008-12-19 19:13:09 +00001123 // Check argument types.
1124 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1125 ArgIdx != NumArgs; ++ArgIdx) {
1126 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1127 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1128 if (Context.getCanonicalType(FromArgType)
1129 == Context.getCanonicalType(ToArgType)) {
1130 // Okay, the types match exactly. Nothing to do.
1131 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1132 ConvertedType, IncompatibleObjC)) {
1133 // Okay, we have an Objective-C pointer conversion.
1134 HasObjCConversion = true;
1135 } else {
1136 // Argument types are too different. Abort.
1137 return false;
1138 }
1139 }
1140
1141 if (HasObjCConversion) {
1142 // We had an Objective-C conversion. Allow this pointer
1143 // conversion, but complain about it.
1144 ConvertedType = ToType;
1145 IncompatibleObjC = true;
1146 return true;
1147 }
1148 }
1149
Sebastian Redl72b597d2009-01-25 19:43:20 +00001150 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001151}
1152
Douglas Gregor39c16d42008-10-24 04:54:22 +00001153/// CheckPointerConversion - Check the pointer conversion from the
1154/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001155/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001156/// conversions for which IsPointerConversion has already returned
1157/// true. It returns true and produces a diagnostic if there was an
1158/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001159bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001160 CastExpr::CastKind &Kind,
1161 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001162 QualType FromType = From->getType();
1163
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001164 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1165 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001166 QualType FromPointeeType = FromPtrType->getPointeeType(),
1167 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001168
Douglas Gregor39c16d42008-10-24 04:54:22 +00001169 if (FromPointeeType->isRecordType() &&
1170 ToPointeeType->isRecordType()) {
1171 // We must have a derived-to-base conversion. Check an
1172 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001173 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1174 From->getExprLoc(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001175 From->getSourceRange(),
1176 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001177 return true;
1178
1179 // The conversion was successful.
1180 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001181 }
1182 }
Mike Stump11289f42009-09-09 15:08:12 +00001183 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001184 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001185 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001186 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001187 // Objective-C++ conversions are always okay.
1188 // FIXME: We should have a different class of conversions for the
1189 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001190 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001191 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001192
Steve Naroff7cae42b2009-07-10 23:34:53 +00001193 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001194 return false;
1195}
1196
Sebastian Redl72b597d2009-01-25 19:43:20 +00001197/// IsMemberPointerConversion - Determines whether the conversion of the
1198/// expression From, which has the (possibly adjusted) type FromType, can be
1199/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1200/// If so, returns true and places the converted type (that might differ from
1201/// ToType in its cv-qualifiers at some level) into ConvertedType.
1202bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001203 QualType ToType,
1204 bool InOverloadResolution,
1205 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001206 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001207 if (!ToTypePtr)
1208 return false;
1209
1210 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001211 if (From->isNullPointerConstant(Context,
1212 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1213 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001214 ConvertedType = ToType;
1215 return true;
1216 }
1217
1218 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001219 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001220 if (!FromTypePtr)
1221 return false;
1222
1223 // A pointer to member of B can be converted to a pointer to member of D,
1224 // where D is derived from B (C++ 4.11p2).
1225 QualType FromClass(FromTypePtr->getClass(), 0);
1226 QualType ToClass(ToTypePtr->getClass(), 0);
1227 // FIXME: What happens when these are dependent? Is this function even called?
1228
1229 if (IsDerivedFrom(ToClass, FromClass)) {
1230 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1231 ToClass.getTypePtr());
1232 return true;
1233 }
1234
1235 return false;
1236}
1237
1238/// CheckMemberPointerConversion - Check the member pointer conversion from the
1239/// expression From to the type ToType. This routine checks for ambiguous or
1240/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1241/// for which IsMemberPointerConversion has already returned true. It returns
1242/// true and produces a diagnostic if there was an error, or returns false
1243/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001244bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001245 CastExpr::CastKind &Kind,
1246 bool IgnoreBaseAccess) {
1247 (void)IgnoreBaseAccess;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001248 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001249 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001250 if (!FromPtrType) {
1251 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001252 assert(From->isNullPointerConstant(Context,
1253 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001254 "Expr must be null pointer constant!");
1255 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001256 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001257 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001258
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001259 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001260 assert(ToPtrType && "No member pointer cast has a target type "
1261 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001262
Sebastian Redled8f2002009-01-28 18:33:18 +00001263 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1264 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001265
Sebastian Redled8f2002009-01-28 18:33:18 +00001266 // FIXME: What about dependent types?
1267 assert(FromClass->isRecordType() && "Pointer into non-class.");
1268 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001269
Douglas Gregor36d1b142009-10-06 17:59:45 +00001270 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1271 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001272 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1273 assert(DerivationOkay &&
1274 "Should not have been called if derivation isn't OK.");
1275 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001276
Sebastian Redled8f2002009-01-28 18:33:18 +00001277 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1278 getUnqualifiedType())) {
1279 // Derivation is ambiguous. Redo the check to find the exact paths.
1280 Paths.clear();
1281 Paths.setRecordingPaths(true);
1282 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1283 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1284 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001285
Sebastian Redled8f2002009-01-28 18:33:18 +00001286 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1287 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1288 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1289 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001290 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001291
Douglas Gregor89ee6822009-02-28 01:32:25 +00001292 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001293 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1294 << FromClass << ToClass << QualType(VBase, 0)
1295 << From->getSourceRange();
1296 return true;
1297 }
1298
Anders Carlssond7923c62009-08-22 23:33:40 +00001299 // Must be a base to derived member conversion.
1300 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001301 return false;
1302}
1303
Douglas Gregor9a657932008-10-21 23:43:52 +00001304/// IsQualificationConversion - Determines whether the conversion from
1305/// an rvalue of type FromType to ToType is a qualification conversion
1306/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001307bool
1308Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001309 FromType = Context.getCanonicalType(FromType);
1310 ToType = Context.getCanonicalType(ToType);
1311
1312 // If FromType and ToType are the same type, this is not a
1313 // qualification conversion.
1314 if (FromType == ToType)
1315 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001316
Douglas Gregor9a657932008-10-21 23:43:52 +00001317 // (C++ 4.4p4):
1318 // A conversion can add cv-qualifiers at levels other than the first
1319 // in multi-level pointers, subject to the following rules: [...]
1320 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001321 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001322 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001323 // Within each iteration of the loop, we check the qualifiers to
1324 // determine if this still looks like a qualification
1325 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001326 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001327 // until there are no more pointers or pointers-to-members left to
1328 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001329 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001330
1331 // -- for every j > 0, if const is in cv 1,j then const is in cv
1332 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001333 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001334 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001335
Douglas Gregor9a657932008-10-21 23:43:52 +00001336 // -- if the cv 1,j and cv 2,j are different, then const is in
1337 // every cv for 0 < k < j.
1338 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001339 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001340 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001341
Douglas Gregor9a657932008-10-21 23:43:52 +00001342 // Keep track of whether all prior cv-qualifiers in the "to" type
1343 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001344 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001345 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001346 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001347
1348 // We are left with FromType and ToType being the pointee types
1349 // after unwrapping the original FromType and ToType the same number
1350 // of types. If we unwrapped any pointers, and if FromType and
1351 // ToType have the same unqualified type (since we checked
1352 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001353 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001354}
1355
Douglas Gregor576e98c2009-01-30 23:27:23 +00001356/// Determines whether there is a user-defined conversion sequence
1357/// (C++ [over.ics.user]) that converts expression From to the type
1358/// ToType. If such a conversion exists, User will contain the
1359/// user-defined conversion sequence that performs such a conversion
1360/// and this routine will return true. Otherwise, this routine returns
1361/// false and User is unspecified.
1362///
1363/// \param AllowConversionFunctions true if the conversion should
1364/// consider conversion functions at all. If false, only constructors
1365/// will be considered.
1366///
1367/// \param AllowExplicit true if the conversion should consider C++0x
1368/// "explicit" conversion functions as well as non-explicit conversion
1369/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001370///
1371/// \param ForceRValue true if the expression should be treated as an rvalue
1372/// for overload resolution.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001373/// \param UserCast true if looking for user defined conversion for a static
1374/// cast.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001375Sema::OverloadingResult Sema::IsUserDefinedConversion(
1376 Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001377 UserDefinedConversionSequence& User,
Fariborz Jahanian19c73282009-09-15 00:10:11 +00001378 OverloadCandidateSet& CandidateSet,
Douglas Gregor576e98c2009-01-30 23:27:23 +00001379 bool AllowConversionFunctions,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001380 bool AllowExplicit, bool ForceRValue,
1381 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001382 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001383 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1384 // We're not going to find any constructors.
1385 } else if (CXXRecordDecl *ToRecordDecl
1386 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001387 // C++ [over.match.ctor]p1:
1388 // When objects of class type are direct-initialized (8.5), or
1389 // copy-initialized from an expression of the same or a
1390 // derived class type (8.5), overload resolution selects the
1391 // constructor. [...] For copy-initialization, the candidate
1392 // functions are all the converting constructors (12.3.1) of
1393 // that class. The argument list is the expression-list within
1394 // the parentheses of the initializer.
Douglas Gregor379d84b2009-11-13 18:44:21 +00001395 bool SuppressUserConversions = !UserCast;
1396 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1397 IsDerivedFrom(From->getType(), ToType)) {
1398 SuppressUserConversions = false;
1399 AllowConversionFunctions = false;
1400 }
1401
Mike Stump11289f42009-09-09 15:08:12 +00001402 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001403 = Context.DeclarationNames.getCXXConstructorName(
1404 Context.getCanonicalType(ToType).getUnqualifiedType());
1405 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001406 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001407 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001408 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001409 // Find the constructor (which may be a template).
1410 CXXConstructorDecl *Constructor = 0;
1411 FunctionTemplateDecl *ConstructorTmpl
1412 = dyn_cast<FunctionTemplateDecl>(*Con);
1413 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001414 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001415 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1416 else
1417 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001418
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001419 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001420 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001421 if (ConstructorTmpl)
John McCall6b51f282009-11-23 01:53:49 +00001422 AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
1423 &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001424 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001425 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001426 // Allow one user-defined conversion when user specifies a
1427 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001428 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001429 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001430 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001431 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001432 }
1433 }
1434
Douglas Gregor576e98c2009-01-30 23:27:23 +00001435 if (!AllowConversionFunctions) {
1436 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001437 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1438 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001439 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001440 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001441 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001442 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001443 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001444 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1445 // Add all of the conversion functions as candidates.
John McCalld14a8642009-11-21 08:51:07 +00001446 const UnresolvedSet *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001447 = FromRecordDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00001448 for (UnresolvedSet::iterator I = Conversions->begin(),
1449 E = Conversions->end(); I != E; ++I) {
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001450 CXXConversionDecl *Conv;
1451 FunctionTemplateDecl *ConvTemplate;
John McCalld14a8642009-11-21 08:51:07 +00001452 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001453 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1454 else
John McCalld14a8642009-11-21 08:51:07 +00001455 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001456
1457 if (AllowExplicit || !Conv->isExplicit()) {
1458 if (ConvTemplate)
1459 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1460 CandidateSet);
1461 else
1462 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1463 }
1464 }
1465 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001466 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001467
1468 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001469 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001470 case OR_Success:
1471 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001472 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001473 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1474 // C++ [over.ics.user]p1:
1475 // If the user-defined conversion is specified by a
1476 // constructor (12.3.1), the initial standard conversion
1477 // sequence converts the source type to the type required by
1478 // the argument of the constructor.
1479 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001480 QualType ThisType = Constructor->getThisType(Context);
Fariborz Jahanian55824512009-11-06 00:23:08 +00001481 if (Best->Conversions[0].ConversionKind ==
1482 ImplicitConversionSequence::EllipsisConversion)
1483 User.EllipsisConversion = true;
1484 else {
1485 User.Before = Best->Conversions[0].Standard;
1486 User.EllipsisConversion = false;
1487 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001488 User.ConversionFunction = Constructor;
1489 User.After.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00001490 User.After.FromTypePtr
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001491 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001492 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001493 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001494 } else if (CXXConversionDecl *Conversion
1495 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1496 // C++ [over.ics.user]p1:
1497 //
1498 // [...] If the user-defined conversion is specified by a
1499 // conversion function (12.3.2), the initial standard
1500 // conversion sequence converts the source type to the
1501 // implicit object parameter of the conversion function.
1502 User.Before = Best->Conversions[0].Standard;
1503 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001504 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001505
1506 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001507 // The second standard conversion sequence converts the
1508 // result of the user-defined conversion to the target type
1509 // for the sequence. Since an implicit conversion sequence
1510 // is an initialization, the special rules for
1511 // initialization by user-defined conversion apply when
1512 // selecting the best user-defined conversion for a
1513 // user-defined conversion sequence (see 13.3.3 and
1514 // 13.3.3.1).
1515 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001516 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001517 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001518 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001519 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001520 }
Mike Stump11289f42009-09-09 15:08:12 +00001521
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001522 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001523 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001524 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001525 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001526 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001527
1528 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001529 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001530 }
1531
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001532 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001533}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001534
1535bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001536Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001537 ImplicitConversionSequence ICS;
1538 OverloadCandidateSet CandidateSet;
1539 OverloadingResult OvResult =
1540 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1541 CandidateSet, true, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001542 if (OvResult == OR_Ambiguous)
1543 Diag(From->getSourceRange().getBegin(),
1544 diag::err_typecheck_ambiguous_condition)
1545 << From->getType() << ToType << From->getSourceRange();
1546 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1547 Diag(From->getSourceRange().getBegin(),
1548 diag::err_typecheck_nonviable_condition)
1549 << From->getType() << ToType << From->getSourceRange();
1550 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001551 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00001552 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001553 return true;
1554}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001555
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001556/// CompareImplicitConversionSequences - Compare two implicit
1557/// conversion sequences to determine whether one is better than the
1558/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001559ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001560Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1561 const ImplicitConversionSequence& ICS2)
1562{
1563 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1564 // conversion sequences (as defined in 13.3.3.1)
1565 // -- a standard conversion sequence (13.3.3.1.1) is a better
1566 // conversion sequence than a user-defined conversion sequence or
1567 // an ellipsis conversion sequence, and
1568 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1569 // conversion sequence than an ellipsis conversion sequence
1570 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001571 //
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001572 if (ICS1.ConversionKind < ICS2.ConversionKind)
1573 return ImplicitConversionSequence::Better;
1574 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1575 return ImplicitConversionSequence::Worse;
1576
1577 // Two implicit conversion sequences of the same form are
1578 // indistinguishable conversion sequences unless one of the
1579 // following rules apply: (C++ 13.3.3.2p3):
1580 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1581 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump11289f42009-09-09 15:08:12 +00001582 else if (ICS1.ConversionKind ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001583 ImplicitConversionSequence::UserDefinedConversion) {
1584 // User-defined conversion sequence U1 is a better conversion
1585 // sequence than another user-defined conversion sequence U2 if
1586 // they contain the same user-defined conversion function or
1587 // constructor and if the second standard conversion sequence of
1588 // U1 is better than the second standard conversion sequence of
1589 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001590 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001591 ICS2.UserDefined.ConversionFunction)
1592 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1593 ICS2.UserDefined.After);
1594 }
1595
1596 return ImplicitConversionSequence::Indistinguishable;
1597}
1598
1599/// CompareStandardConversionSequences - Compare two standard
1600/// conversion sequences to determine whether one is better than the
1601/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001602ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001603Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1604 const StandardConversionSequence& SCS2)
1605{
1606 // Standard conversion sequence S1 is a better conversion sequence
1607 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1608
1609 // -- S1 is a proper subsequence of S2 (comparing the conversion
1610 // sequences in the canonical form defined by 13.3.3.1.1,
1611 // excluding any Lvalue Transformation; the identity conversion
1612 // sequence is considered to be a subsequence of any
1613 // non-identity conversion sequence) or, if not that,
1614 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1615 // Neither is a proper subsequence of the other. Do nothing.
1616 ;
1617 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1618 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001619 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001620 SCS1.Third == ICK_Identity))
1621 // SCS1 is a proper subsequence of SCS2.
1622 return ImplicitConversionSequence::Better;
1623 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1624 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001625 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001626 SCS2.Third == ICK_Identity))
1627 // SCS2 is a proper subsequence of SCS1.
1628 return ImplicitConversionSequence::Worse;
1629
1630 // -- the rank of S1 is better than the rank of S2 (by the rules
1631 // defined below), or, if not that,
1632 ImplicitConversionRank Rank1 = SCS1.getRank();
1633 ImplicitConversionRank Rank2 = SCS2.getRank();
1634 if (Rank1 < Rank2)
1635 return ImplicitConversionSequence::Better;
1636 else if (Rank2 < Rank1)
1637 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001638
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001639 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1640 // are indistinguishable unless one of the following rules
1641 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001642
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001643 // A conversion that is not a conversion of a pointer, or
1644 // pointer to member, to bool is better than another conversion
1645 // that is such a conversion.
1646 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1647 return SCS2.isPointerConversionToBool()
1648 ? ImplicitConversionSequence::Better
1649 : ImplicitConversionSequence::Worse;
1650
Douglas Gregor5c407d92008-10-23 00:40:37 +00001651 // C++ [over.ics.rank]p4b2:
1652 //
1653 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001654 // conversion of B* to A* is better than conversion of B* to
1655 // void*, and conversion of A* to void* is better than conversion
1656 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001657 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001658 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001659 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001660 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001661 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1662 // Exactly one of the conversion sequences is a conversion to
1663 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001664 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1665 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001666 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1667 // Neither conversion sequence converts to a void pointer; compare
1668 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001669 if (ImplicitConversionSequence::CompareKind DerivedCK
1670 = CompareDerivedToBaseConversions(SCS1, SCS2))
1671 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001672 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1673 // Both conversion sequences are conversions to void
1674 // pointers. Compare the source types to determine if there's an
1675 // inheritance relationship in their sources.
1676 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1677 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1678
1679 // Adjust the types we're converting from via the array-to-pointer
1680 // conversion, if we need to.
1681 if (SCS1.First == ICK_Array_To_Pointer)
1682 FromType1 = Context.getArrayDecayedType(FromType1);
1683 if (SCS2.First == ICK_Array_To_Pointer)
1684 FromType2 = Context.getArrayDecayedType(FromType2);
1685
Mike Stump11289f42009-09-09 15:08:12 +00001686 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001687 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001688 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001689 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001690
1691 if (IsDerivedFrom(FromPointee2, FromPointee1))
1692 return ImplicitConversionSequence::Better;
1693 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1694 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001695
1696 // Objective-C++: If one interface is more specific than the
1697 // other, it is the better one.
John McCall9dd450b2009-09-21 23:43:11 +00001698 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1699 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001700 if (FromIface1 && FromIface1) {
1701 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1702 return ImplicitConversionSequence::Better;
1703 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1704 return ImplicitConversionSequence::Worse;
1705 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001706 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001707
1708 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1709 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001710 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001711 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001712 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001713
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001714 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001715 // C++0x [over.ics.rank]p3b4:
1716 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1717 // implicit object parameter of a non-static member function declared
1718 // without a ref-qualifier, and S1 binds an rvalue reference to an
1719 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001720 // FIXME: We don't know if we're dealing with the implicit object parameter,
1721 // or if the member function in this case has a ref qualifier.
1722 // (Of course, we don't have ref qualifiers yet.)
1723 if (SCS1.RRefBinding != SCS2.RRefBinding)
1724 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1725 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001726
1727 // C++ [over.ics.rank]p3b4:
1728 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1729 // which the references refer are the same type except for
1730 // top-level cv-qualifiers, and the type to which the reference
1731 // initialized by S2 refers is more cv-qualified than the type
1732 // to which the reference initialized by S1 refers.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001733 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1734 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001735 T1 = Context.getCanonicalType(T1);
1736 T2 = Context.getCanonicalType(T2);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001737 if (Context.hasSameUnqualifiedType(T1, T2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001738 if (T2.isMoreQualifiedThan(T1))
1739 return ImplicitConversionSequence::Better;
1740 else if (T1.isMoreQualifiedThan(T2))
1741 return ImplicitConversionSequence::Worse;
1742 }
1743 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001744
1745 return ImplicitConversionSequence::Indistinguishable;
1746}
1747
1748/// CompareQualificationConversions - Compares two standard conversion
1749/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001750/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1751ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001752Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001753 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001754 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001755 // -- S1 and S2 differ only in their qualification conversion and
1756 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1757 // cv-qualification signature of type T1 is a proper subset of
1758 // the cv-qualification signature of type T2, and S1 is not the
1759 // deprecated string literal array-to-pointer conversion (4.2).
1760 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1761 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1762 return ImplicitConversionSequence::Indistinguishable;
1763
1764 // FIXME: the example in the standard doesn't use a qualification
1765 // conversion (!)
1766 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1767 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1768 T1 = Context.getCanonicalType(T1);
1769 T2 = Context.getCanonicalType(T2);
1770
1771 // If the types are the same, we won't learn anything by unwrapped
1772 // them.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001773 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001774 return ImplicitConversionSequence::Indistinguishable;
1775
Mike Stump11289f42009-09-09 15:08:12 +00001776 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001777 = ImplicitConversionSequence::Indistinguishable;
1778 while (UnwrapSimilarPointerTypes(T1, T2)) {
1779 // Within each iteration of the loop, we check the qualifiers to
1780 // determine if this still looks like a qualification
1781 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001782 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001783 // until there are no more pointers or pointers-to-members left
1784 // to unwrap. This essentially mimics what
1785 // IsQualificationConversion does, but here we're checking for a
1786 // strict subset of qualifiers.
1787 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1788 // The qualifiers are the same, so this doesn't tell us anything
1789 // about how the sequences rank.
1790 ;
1791 else if (T2.isMoreQualifiedThan(T1)) {
1792 // T1 has fewer qualifiers, so it could be the better sequence.
1793 if (Result == ImplicitConversionSequence::Worse)
1794 // Neither has qualifiers that are a subset of the other's
1795 // qualifiers.
1796 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001797
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001798 Result = ImplicitConversionSequence::Better;
1799 } else if (T1.isMoreQualifiedThan(T2)) {
1800 // T2 has fewer qualifiers, so it could be the better sequence.
1801 if (Result == ImplicitConversionSequence::Better)
1802 // Neither has qualifiers that are a subset of the other's
1803 // qualifiers.
1804 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001805
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001806 Result = ImplicitConversionSequence::Worse;
1807 } else {
1808 // Qualifiers are disjoint.
1809 return ImplicitConversionSequence::Indistinguishable;
1810 }
1811
1812 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001813 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001814 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001815 }
1816
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001817 // Check that the winning standard conversion sequence isn't using
1818 // the deprecated string literal array to pointer conversion.
1819 switch (Result) {
1820 case ImplicitConversionSequence::Better:
1821 if (SCS1.Deprecated)
1822 Result = ImplicitConversionSequence::Indistinguishable;
1823 break;
1824
1825 case ImplicitConversionSequence::Indistinguishable:
1826 break;
1827
1828 case ImplicitConversionSequence::Worse:
1829 if (SCS2.Deprecated)
1830 Result = ImplicitConversionSequence::Indistinguishable;
1831 break;
1832 }
1833
1834 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001835}
1836
Douglas Gregor5c407d92008-10-23 00:40:37 +00001837/// CompareDerivedToBaseConversions - Compares two standard conversion
1838/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001839/// various kinds of derived-to-base conversions (C++
1840/// [over.ics.rank]p4b3). As part of these checks, we also look at
1841/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001842ImplicitConversionSequence::CompareKind
1843Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1844 const StandardConversionSequence& SCS2) {
1845 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1846 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1847 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1848 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1849
1850 // Adjust the types we're converting from via the array-to-pointer
1851 // conversion, if we need to.
1852 if (SCS1.First == ICK_Array_To_Pointer)
1853 FromType1 = Context.getArrayDecayedType(FromType1);
1854 if (SCS2.First == ICK_Array_To_Pointer)
1855 FromType2 = Context.getArrayDecayedType(FromType2);
1856
1857 // Canonicalize all of the types.
1858 FromType1 = Context.getCanonicalType(FromType1);
1859 ToType1 = Context.getCanonicalType(ToType1);
1860 FromType2 = Context.getCanonicalType(FromType2);
1861 ToType2 = Context.getCanonicalType(ToType2);
1862
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001863 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001864 //
1865 // If class B is derived directly or indirectly from class A and
1866 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001867 //
1868 // For Objective-C, we let A, B, and C also be Objective-C
1869 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001870
1871 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00001872 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00001873 SCS2.Second == ICK_Pointer_Conversion &&
1874 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1875 FromType1->isPointerType() && FromType2->isPointerType() &&
1876 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001877 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001878 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001879 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001880 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001881 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001882 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001883 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001884 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001885
John McCall9dd450b2009-09-21 23:43:11 +00001886 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1887 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1888 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1889 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001890
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001891 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00001892 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1893 if (IsDerivedFrom(ToPointee1, ToPointee2))
1894 return ImplicitConversionSequence::Better;
1895 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1896 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001897
1898 if (ToIface1 && ToIface2) {
1899 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1900 return ImplicitConversionSequence::Better;
1901 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1902 return ImplicitConversionSequence::Worse;
1903 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001904 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001905
1906 // -- conversion of B* to A* is better than conversion of C* to A*,
1907 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1908 if (IsDerivedFrom(FromPointee2, FromPointee1))
1909 return ImplicitConversionSequence::Better;
1910 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1911 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00001912
Douglas Gregor237f96c2008-11-26 23:31:11 +00001913 if (FromIface1 && FromIface2) {
1914 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1915 return ImplicitConversionSequence::Better;
1916 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1917 return ImplicitConversionSequence::Worse;
1918 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001919 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001920 }
1921
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001922 // Compare based on reference bindings.
1923 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1924 SCS1.Second == ICK_Derived_To_Base) {
1925 // -- binding of an expression of type C to a reference of type
1926 // B& is better than binding an expression of type C to a
1927 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001928 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1929 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001930 if (IsDerivedFrom(ToType1, ToType2))
1931 return ImplicitConversionSequence::Better;
1932 else if (IsDerivedFrom(ToType2, ToType1))
1933 return ImplicitConversionSequence::Worse;
1934 }
1935
Douglas Gregor2fe98832008-11-03 19:09:14 +00001936 // -- binding of an expression of type B to a reference of type
1937 // A& is better than binding an expression of type C to a
1938 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001939 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1940 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001941 if (IsDerivedFrom(FromType2, FromType1))
1942 return ImplicitConversionSequence::Better;
1943 else if (IsDerivedFrom(FromType1, FromType2))
1944 return ImplicitConversionSequence::Worse;
1945 }
1946 }
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00001947
1948 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00001949 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
1950 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
1951 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
1952 const MemberPointerType * FromMemPointer1 =
1953 FromType1->getAs<MemberPointerType>();
1954 const MemberPointerType * ToMemPointer1 =
1955 ToType1->getAs<MemberPointerType>();
1956 const MemberPointerType * FromMemPointer2 =
1957 FromType2->getAs<MemberPointerType>();
1958 const MemberPointerType * ToMemPointer2 =
1959 ToType2->getAs<MemberPointerType>();
1960 const Type *FromPointeeType1 = FromMemPointer1->getClass();
1961 const Type *ToPointeeType1 = ToMemPointer1->getClass();
1962 const Type *FromPointeeType2 = FromMemPointer2->getClass();
1963 const Type *ToPointeeType2 = ToMemPointer2->getClass();
1964 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
1965 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
1966 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
1967 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00001968 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00001969 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1970 if (IsDerivedFrom(ToPointee1, ToPointee2))
1971 return ImplicitConversionSequence::Worse;
1972 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1973 return ImplicitConversionSequence::Better;
1974 }
1975 // conversion of B::* to C::* is better than conversion of A::* to C::*
1976 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
1977 if (IsDerivedFrom(FromPointee1, FromPointee2))
1978 return ImplicitConversionSequence::Better;
1979 else if (IsDerivedFrom(FromPointee2, FromPointee1))
1980 return ImplicitConversionSequence::Worse;
1981 }
1982 }
1983
Douglas Gregor2fe98832008-11-03 19:09:14 +00001984 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1985 SCS1.Second == ICK_Derived_To_Base) {
1986 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001987 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1988 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00001989 if (IsDerivedFrom(ToType1, ToType2))
1990 return ImplicitConversionSequence::Better;
1991 else if (IsDerivedFrom(ToType2, ToType1))
1992 return ImplicitConversionSequence::Worse;
1993 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001994
Douglas Gregor2fe98832008-11-03 19:09:14 +00001995 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001996 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1997 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00001998 if (IsDerivedFrom(FromType2, FromType1))
1999 return ImplicitConversionSequence::Better;
2000 else if (IsDerivedFrom(FromType1, FromType2))
2001 return ImplicitConversionSequence::Worse;
2002 }
2003 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002004
Douglas Gregor5c407d92008-10-23 00:40:37 +00002005 return ImplicitConversionSequence::Indistinguishable;
2006}
2007
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002008/// TryCopyInitialization - Try to copy-initialize a value of type
2009/// ToType from the expression From. Return the implicit conversion
2010/// sequence required to pass this argument, which may be a bad
2011/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002012/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00002013/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2014/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00002015ImplicitConversionSequence
2016Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002017 bool SuppressUserConversions, bool ForceRValue,
2018 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002019 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002020 ImplicitConversionSequence ICS;
Mike Stump11289f42009-09-09 15:08:12 +00002021 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002022 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002023 SuppressUserConversions,
2024 /*AllowExplicit=*/false,
2025 ForceRValue,
2026 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002027 return ICS;
2028 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002029 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002030 SuppressUserConversions,
2031 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002032 ForceRValue,
2033 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002034 }
2035}
2036
Sebastian Redl42e92c42009-04-12 17:16:29 +00002037/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2038/// the expression @p From. Returns true (and emits a diagnostic) if there was
2039/// an error, returns false if the initialization succeeded. Elidable should
2040/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2041/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002042bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002043 const char* Flavor, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002044 if (!getLangOptions().CPlusPlus) {
2045 // In C, argument passing is the same as performing an assignment.
2046 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002047
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002048 AssignConvertType ConvTy =
2049 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002050 if (ConvTy != Compatible &&
2051 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2052 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002053
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002054 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2055 FromType, From, Flavor);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002056 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002057
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002058 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002059 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002060 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002061 /*SuppressUserConversions=*/false,
2062 /*AllowExplicit=*/false,
2063 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002064
Sebastian Redl42e92c42009-04-12 17:16:29 +00002065 if (!PerformImplicitConversion(From, ToType, Flavor,
2066 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002067 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00002068 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002069 return Diag(From->getSourceRange().getBegin(),
2070 diag::err_typecheck_convert_incompatible)
2071 << ToType << From->getType() << Flavor << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002072 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002073}
2074
Douglas Gregor436424c2008-11-18 23:14:02 +00002075/// TryObjectArgumentInitialization - Try to initialize the object
2076/// parameter of the given member function (@c Method) from the
2077/// expression @p From.
2078ImplicitConversionSequence
2079Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
2080 QualType ClassType = Context.getTypeDeclType(Method->getParent());
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002081 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2082 // const volatile object.
2083 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2084 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2085 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002086
2087 // Set up the conversion sequence as a "bad" conversion, to allow us
2088 // to exit early.
2089 ImplicitConversionSequence ICS;
2090 ICS.Standard.setAsIdentityConversion();
2091 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2092
2093 // We need to have an object of class type.
2094 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002095 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002096 FromType = PT->getPointeeType();
2097
2098 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002099
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002100 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002101 // where X is the class of which the function is a member
2102 // (C++ [over.match.funcs]p4). However, when finding an implicit
2103 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002104 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002105 // (C++ [over.match.funcs]p5). We perform a simplified version of
2106 // reference binding here, that allows class rvalues to bind to
2107 // non-constant references.
2108
2109 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2110 // with the implicit object parameter (C++ [over.match.funcs]p5).
2111 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002112 if (ImplicitParamType.getCVRQualifiers()
2113 != FromTypeCanon.getLocalCVRQualifiers() &&
Douglas Gregor01df9462009-11-05 00:07:36 +00002114 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon))
Douglas Gregor436424c2008-11-18 23:14:02 +00002115 return ICS;
2116
2117 // Check that we have either the same type or a derived type. It
2118 // affects the conversion rank.
2119 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002120 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor436424c2008-11-18 23:14:02 +00002121 ICS.Standard.Second = ICK_Identity;
2122 else if (IsDerivedFrom(FromType, ClassType))
2123 ICS.Standard.Second = ICK_Derived_To_Base;
2124 else
2125 return ICS;
2126
2127 // Success. Mark this as a reference binding.
2128 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2129 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2130 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2131 ICS.Standard.ReferenceBinding = true;
2132 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002133 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002134 return ICS;
2135}
2136
2137/// PerformObjectArgumentInitialization - Perform initialization of
2138/// the implicit object parameter for the given Method with the given
2139/// expression.
2140bool
2141Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002142 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002143 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002144 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002145
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002146 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002147 FromRecordType = PT->getPointeeType();
2148 DestType = Method->getThisType(Context);
2149 } else {
2150 FromRecordType = From->getType();
2151 DestType = ImplicitParamRecordType;
2152 }
2153
Mike Stump11289f42009-09-09 15:08:12 +00002154 ImplicitConversionSequence ICS
Douglas Gregor436424c2008-11-18 23:14:02 +00002155 = TryObjectArgumentInitialization(From, Method);
2156 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2157 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002158 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002159 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002160
Douglas Gregor436424c2008-11-18 23:14:02 +00002161 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002162 CheckDerivedToBaseConversion(FromRecordType,
2163 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002164 From->getSourceRange().getBegin(),
2165 From->getSourceRange()))
2166 return true;
2167
Mike Stump11289f42009-09-09 15:08:12 +00002168 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002169 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002170 return false;
2171}
2172
Douglas Gregor5fb53972009-01-14 15:45:31 +00002173/// TryContextuallyConvertToBool - Attempt to contextually convert the
2174/// expression From to bool (C++0x [conv]p3).
2175ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002176 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002177 // FIXME: Are these flags correct?
2178 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002179 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002180 /*ForceRValue=*/false,
2181 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002182}
2183
2184/// PerformContextuallyConvertToBool - Perform a contextual conversion
2185/// of the expression From to bool (C++0x [conv]p3).
2186bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2187 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2188 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2189 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002190
Fariborz Jahanian76197412009-11-18 18:26:29 +00002191 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002192 return Diag(From->getSourceRange().getBegin(),
2193 diag::err_typecheck_bool_condition)
2194 << From->getType() << From->getSourceRange();
2195 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002196}
2197
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002198/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002199/// candidate functions, using the given function call arguments. If
2200/// @p SuppressUserConversions, then don't allow user-defined
2201/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002202/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2203/// hacky way to implement the overloading rules for elidable copy
2204/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002205///
2206/// \para PartialOverloading true if we are performing "partial" overloading
2207/// based on an incomplete set of function arguments. This feature is used by
2208/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002209void
2210Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002211 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002212 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002213 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002214 bool ForceRValue,
2215 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002216 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002217 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002218 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002219 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002220 "Use AddConversionCandidate for conversion functions");
Mike Stump11289f42009-09-09 15:08:12 +00002221 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002222 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002223
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002224 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002225 if (!isa<CXXConstructorDecl>(Method)) {
2226 // If we get here, it's because we're calling a member function
2227 // that is named without a member access expression (e.g.,
2228 // "this->f") that was either written explicitly or created
2229 // implicitly. This can happen with a qualified call to a member
2230 // function, e.g., X::f(). We use a NULL object as the implied
2231 // object argument (C++ [over.call.func]p3).
Mike Stump11289f42009-09-09 15:08:12 +00002232 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002233 SuppressUserConversions, ForceRValue);
2234 return;
2235 }
2236 // We treat a constructor like a non-member function, since its object
2237 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002238 }
2239
Douglas Gregorff7028a2009-11-13 23:59:09 +00002240 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002241 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002242
Douglas Gregor27381f32009-11-23 12:27:39 +00002243 // Overload resolution is always an unevaluated context.
2244 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2245
Douglas Gregorffe14e32009-11-14 01:20:54 +00002246 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2247 // C++ [class.copy]p3:
2248 // A member function template is never instantiated to perform the copy
2249 // of a class object to an object of its class type.
2250 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2251 if (NumArgs == 1 &&
2252 Constructor->isCopyConstructorLikeSpecialization() &&
2253 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2254 return;
2255 }
2256
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002257 // Add this candidate
2258 CandidateSet.push_back(OverloadCandidate());
2259 OverloadCandidate& Candidate = CandidateSet.back();
2260 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002261 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002262 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002263 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002264
2265 unsigned NumArgsInProto = Proto->getNumArgs();
2266
2267 // (C++ 13.3.2p2): A candidate function having fewer than m
2268 // parameters is viable only if it has an ellipsis in its parameter
2269 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002270 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2271 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002272 Candidate.Viable = false;
2273 return;
2274 }
2275
2276 // (C++ 13.3.2p2): A candidate function having more than m parameters
2277 // is viable only if the (m+1)st parameter has a default argument
2278 // (8.3.6). For the purposes of overload resolution, the
2279 // parameter list is truncated on the right, so that there are
2280 // exactly m parameters.
2281 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002282 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002283 // Not enough arguments.
2284 Candidate.Viable = false;
2285 return;
2286 }
2287
2288 // Determine the implicit conversion sequences for each of the
2289 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002290 Candidate.Conversions.resize(NumArgs);
2291 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2292 if (ArgIdx < NumArgsInProto) {
2293 // (C++ 13.3.2p3): for F to be a viable function, there shall
2294 // exist for each argument an implicit conversion sequence
2295 // (13.3.3.1) that converts that argument to the corresponding
2296 // parameter of F.
2297 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002298 Candidate.Conversions[ArgIdx]
2299 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002300 SuppressUserConversions, ForceRValue,
2301 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002302 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002303 == ImplicitConversionSequence::BadConversion) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002304 // 13.3.3.1-p10 If several different sequences of conversions exist that
2305 // each convert the argument to the parameter type, the implicit conversion
2306 // sequence associated with the parameter is defined to be the unique conversion
2307 // sequence designated the ambiguous conversion sequence. For the purpose of
2308 // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2309 // conversion sequence is treated as a user-defined sequence that is
2310 // indistinguishable from any other user-defined conversion sequence
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002311 if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002312 Candidate.Conversions[ArgIdx].ConversionKind =
2313 ImplicitConversionSequence::UserDefinedConversion;
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002314 // Set the conversion function to one of them. As due to ambiguity,
2315 // they carry the same weight and is needed for overload resolution
2316 // later.
2317 Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2318 Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2319 }
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002320 else {
2321 Candidate.Viable = false;
2322 break;
2323 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002324 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002325 } else {
2326 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2327 // argument for which there is no corresponding parameter is
2328 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002329 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002330 = ImplicitConversionSequence::EllipsisConversion;
2331 }
2332 }
2333}
2334
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002335/// \brief Add all of the function declarations in the given function set to
2336/// the overload canddiate set.
2337void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2338 Expr **Args, unsigned NumArgs,
2339 OverloadCandidateSet& CandidateSet,
2340 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002341 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002342 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002343 F != FEnd; ++F) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002344 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2345 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2346 AddMethodCandidate(cast<CXXMethodDecl>(FD),
2347 Args[0], Args + 1, NumArgs - 1,
2348 CandidateSet, SuppressUserConversions);
2349 else
2350 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2351 SuppressUserConversions);
2352 } else {
2353 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2354 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2355 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2356 AddMethodTemplateCandidate(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00002357 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002358 Args[0], Args + 1, NumArgs - 1,
2359 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002360 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002361 else
2362 AddTemplateOverloadCandidate(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00002363 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002364 Args, NumArgs, CandidateSet,
2365 SuppressUserConversions);
2366 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002367 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002368}
2369
John McCallf0f1cf02009-11-17 07:50:12 +00002370/// AddMethodCandidate - Adds a named decl (which is some kind of
2371/// method) as a method candidate to the given overload set.
2372void Sema::AddMethodCandidate(NamedDecl *Decl, Expr *Object,
2373 Expr **Args, unsigned NumArgs,
2374 OverloadCandidateSet& CandidateSet,
2375 bool SuppressUserConversions, bool ForceRValue) {
2376
2377 // FIXME: use this
2378 //DeclContext *ActingContext = Decl->getDeclContext();
2379
2380 if (isa<UsingShadowDecl>(Decl))
2381 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2382
2383 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2384 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2385 "Expected a member function template");
John McCall6b51f282009-11-23 01:53:49 +00002386 AddMethodTemplateCandidate(TD, /*ExplicitArgs*/ 0,
John McCallf0f1cf02009-11-17 07:50:12 +00002387 Object, Args, NumArgs,
2388 CandidateSet,
2389 SuppressUserConversions,
2390 ForceRValue);
2391 } else {
2392 AddMethodCandidate(cast<CXXMethodDecl>(Decl), Object, Args, NumArgs,
2393 CandidateSet, SuppressUserConversions, ForceRValue);
2394 }
2395}
2396
Douglas Gregor436424c2008-11-18 23:14:02 +00002397/// AddMethodCandidate - Adds the given C++ member function to the set
2398/// of candidate functions, using the given function call arguments
2399/// and the object argument (@c Object). For example, in a call
2400/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2401/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2402/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002403/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2404/// a slightly hacky way to implement the overloading rules for elidable copy
2405/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002406void
Douglas Gregor436424c2008-11-18 23:14:02 +00002407Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2408 Expr **Args, unsigned NumArgs,
2409 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002410 bool SuppressUserConversions, bool ForceRValue) {
2411 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002412 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002413 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002414 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor436424c2008-11-18 23:14:02 +00002415 "Use AddConversionCandidate for conversion functions");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002416 assert(!isa<CXXConstructorDecl>(Method) &&
2417 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002418
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002419 if (!CandidateSet.isNewCandidate(Method))
2420 return;
2421
Douglas Gregor27381f32009-11-23 12:27:39 +00002422 // Overload resolution is always an unevaluated context.
2423 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2424
Douglas Gregor436424c2008-11-18 23:14:02 +00002425 // Add this candidate
2426 CandidateSet.push_back(OverloadCandidate());
2427 OverloadCandidate& Candidate = CandidateSet.back();
2428 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002429 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002430 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002431
2432 unsigned NumArgsInProto = Proto->getNumArgs();
2433
2434 // (C++ 13.3.2p2): A candidate function having fewer than m
2435 // parameters is viable only if it has an ellipsis in its parameter
2436 // list (8.3.5).
2437 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2438 Candidate.Viable = false;
2439 return;
2440 }
2441
2442 // (C++ 13.3.2p2): A candidate function having more than m parameters
2443 // is viable only if the (m+1)st parameter has a default argument
2444 // (8.3.6). For the purposes of overload resolution, the
2445 // parameter list is truncated on the right, so that there are
2446 // exactly m parameters.
2447 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2448 if (NumArgs < MinRequiredArgs) {
2449 // Not enough arguments.
2450 Candidate.Viable = false;
2451 return;
2452 }
2453
2454 Candidate.Viable = true;
2455 Candidate.Conversions.resize(NumArgs + 1);
2456
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002457 if (Method->isStatic() || !Object)
2458 // The implicit object argument is ignored.
2459 Candidate.IgnoreObjectArgument = true;
2460 else {
2461 // Determine the implicit conversion sequence for the object
2462 // parameter.
2463 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
Mike Stump11289f42009-09-09 15:08:12 +00002464 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002465 == ImplicitConversionSequence::BadConversion) {
2466 Candidate.Viable = false;
2467 return;
2468 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002469 }
2470
2471 // Determine the implicit conversion sequences for each of the
2472 // arguments.
2473 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2474 if (ArgIdx < NumArgsInProto) {
2475 // (C++ 13.3.2p3): for F to be a viable function, there shall
2476 // exist for each argument an implicit conversion sequence
2477 // (13.3.3.1) that converts that argument to the corresponding
2478 // parameter of F.
2479 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002480 Candidate.Conversions[ArgIdx + 1]
2481 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002482 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002483 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002484 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002485 == ImplicitConversionSequence::BadConversion) {
2486 Candidate.Viable = false;
2487 break;
2488 }
2489 } else {
2490 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2491 // argument for which there is no corresponding parameter is
2492 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002493 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002494 = ImplicitConversionSequence::EllipsisConversion;
2495 }
2496 }
2497}
2498
Douglas Gregor97628d62009-08-21 00:16:32 +00002499/// \brief Add a C++ member function template as a candidate to the candidate
2500/// set, using template argument deduction to produce an appropriate member
2501/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002502void
Douglas Gregor97628d62009-08-21 00:16:32 +00002503Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall6b51f282009-11-23 01:53:49 +00002504 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002505 Expr *Object, Expr **Args, unsigned NumArgs,
2506 OverloadCandidateSet& CandidateSet,
2507 bool SuppressUserConversions,
2508 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002509 if (!CandidateSet.isNewCandidate(MethodTmpl))
2510 return;
2511
Douglas Gregor97628d62009-08-21 00:16:32 +00002512 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002513 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002514 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002515 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002516 // candidate functions in the usual way.113) A given name can refer to one
2517 // or more function templates and also to a set of overloaded non-template
2518 // functions. In such a case, the candidate functions generated from each
2519 // function template are combined with the set of non-template candidate
2520 // functions.
2521 TemplateDeductionInfo Info(Context);
2522 FunctionDecl *Specialization = 0;
2523 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002524 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002525 Args, NumArgs, Specialization, Info)) {
2526 // FIXME: Record what happened with template argument deduction, so
2527 // that we can give the user a beautiful diagnostic.
2528 (void)Result;
2529 return;
2530 }
Mike Stump11289f42009-09-09 15:08:12 +00002531
Douglas Gregor97628d62009-08-21 00:16:32 +00002532 // Add the function template specialization produced by template argument
2533 // deduction as a candidate.
2534 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002535 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002536 "Specialization is not a member function?");
Mike Stump11289f42009-09-09 15:08:12 +00002537 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002538 CandidateSet, SuppressUserConversions, ForceRValue);
2539}
2540
Douglas Gregor05155d82009-08-21 23:19:43 +00002541/// \brief Add a C++ function template specialization as a candidate
2542/// in the candidate set, using template argument deduction to produce
2543/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002544void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002545Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00002546 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002547 Expr **Args, unsigned NumArgs,
2548 OverloadCandidateSet& CandidateSet,
2549 bool SuppressUserConversions,
2550 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002551 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2552 return;
2553
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002554 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002555 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002556 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002557 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002558 // candidate functions in the usual way.113) A given name can refer to one
2559 // or more function templates and also to a set of overloaded non-template
2560 // functions. In such a case, the candidate functions generated from each
2561 // function template are combined with the set of non-template candidate
2562 // functions.
2563 TemplateDeductionInfo Info(Context);
2564 FunctionDecl *Specialization = 0;
2565 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002566 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002567 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002568 // FIXME: Record what happened with template argument deduction, so
2569 // that we can give the user a beautiful diagnostic.
2570 (void)Result;
2571 return;
2572 }
Mike Stump11289f42009-09-09 15:08:12 +00002573
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002574 // Add the function template specialization produced by template argument
2575 // deduction as a candidate.
2576 assert(Specialization && "Missing function template specialization?");
2577 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2578 SuppressUserConversions, ForceRValue);
2579}
Mike Stump11289f42009-09-09 15:08:12 +00002580
Douglas Gregora1f013e2008-11-07 22:36:19 +00002581/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002582/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002583/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002584/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002585/// (which may or may not be the same type as the type that the
2586/// conversion function produces).
2587void
2588Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2589 Expr *From, QualType ToType,
2590 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002591 assert(!Conversion->getDescribedFunctionTemplate() &&
2592 "Conversion function templates use AddTemplateConversionCandidate");
2593
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002594 if (!CandidateSet.isNewCandidate(Conversion))
2595 return;
2596
Douglas Gregor27381f32009-11-23 12:27:39 +00002597 // Overload resolution is always an unevaluated context.
2598 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2599
Douglas Gregora1f013e2008-11-07 22:36:19 +00002600 // Add this candidate
2601 CandidateSet.push_back(OverloadCandidate());
2602 OverloadCandidate& Candidate = CandidateSet.back();
2603 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002604 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002605 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002606 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00002607 Candidate.FinalConversion.FromTypePtr
Douglas Gregora1f013e2008-11-07 22:36:19 +00002608 = Conversion->getConversionType().getAsOpaquePtr();
2609 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2610
Douglas Gregor436424c2008-11-18 23:14:02 +00002611 // Determine the implicit conversion sequence for the implicit
2612 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002613 Candidate.Viable = true;
2614 Candidate.Conversions.resize(1);
Douglas Gregor436424c2008-11-18 23:14:02 +00002615 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002616 // Conversion functions to a different type in the base class is visible in
2617 // the derived class. So, a derived to base conversion should not participate
2618 // in overload resolution.
2619 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2620 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump11289f42009-09-09 15:08:12 +00002621 if (Candidate.Conversions[0].ConversionKind
Douglas Gregora1f013e2008-11-07 22:36:19 +00002622 == ImplicitConversionSequence::BadConversion) {
2623 Candidate.Viable = false;
2624 return;
2625 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002626
2627 // We won't go through a user-define type conversion function to convert a
2628 // derived to base as such conversions are given Conversion Rank. They only
2629 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2630 QualType FromCanon
2631 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2632 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2633 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2634 Candidate.Viable = false;
2635 return;
2636 }
2637
Douglas Gregora1f013e2008-11-07 22:36:19 +00002638
2639 // To determine what the conversion from the result of calling the
2640 // conversion function to the type we're eventually trying to
2641 // convert to (ToType), we need to synthesize a call to the
2642 // conversion function and attempt copy initialization from it. This
2643 // makes sure that we get the right semantics with respect to
2644 // lvalues/rvalues and the type. Fortunately, we can allocate this
2645 // call on the stack and we don't need its arguments to be
2646 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002647 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002648 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00002649 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002650 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002651 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002652
2653 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002654 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2655 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002656 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002657 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002658 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002659 ImplicitConversionSequence ICS =
2660 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002661 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002662 /*ForceRValue=*/false,
2663 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002664
Douglas Gregora1f013e2008-11-07 22:36:19 +00002665 switch (ICS.ConversionKind) {
2666 case ImplicitConversionSequence::StandardConversion:
2667 Candidate.FinalConversion = ICS.Standard;
2668 break;
2669
2670 case ImplicitConversionSequence::BadConversion:
2671 Candidate.Viable = false;
2672 break;
2673
2674 default:
Mike Stump11289f42009-09-09 15:08:12 +00002675 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002676 "Can only end up with a standard conversion sequence or failure");
2677 }
2678}
2679
Douglas Gregor05155d82009-08-21 23:19:43 +00002680/// \brief Adds a conversion function template specialization
2681/// candidate to the overload set, using template argument deduction
2682/// to deduce the template arguments of the conversion function
2683/// template from the type that we are converting to (C++
2684/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002685void
Douglas Gregor05155d82009-08-21 23:19:43 +00002686Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2687 Expr *From, QualType ToType,
2688 OverloadCandidateSet &CandidateSet) {
2689 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2690 "Only conversion function templates permitted here");
2691
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002692 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2693 return;
2694
Douglas Gregor05155d82009-08-21 23:19:43 +00002695 TemplateDeductionInfo Info(Context);
2696 CXXConversionDecl *Specialization = 0;
2697 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002698 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002699 Specialization, Info)) {
2700 // FIXME: Record what happened with template argument deduction, so
2701 // that we can give the user a beautiful diagnostic.
2702 (void)Result;
2703 return;
2704 }
Mike Stump11289f42009-09-09 15:08:12 +00002705
Douglas Gregor05155d82009-08-21 23:19:43 +00002706 // Add the conversion function template specialization produced by
2707 // template argument deduction as a candidate.
2708 assert(Specialization && "Missing function template specialization?");
2709 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2710}
2711
Douglas Gregorab7897a2008-11-19 22:57:39 +00002712/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2713/// converts the given @c Object to a function pointer via the
2714/// conversion function @c Conversion, and then attempts to call it
2715/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2716/// the type of function that we'll eventually be calling.
2717void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002718 const FunctionProtoType *Proto,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002719 Expr *Object, Expr **Args, unsigned NumArgs,
2720 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002721 if (!CandidateSet.isNewCandidate(Conversion))
2722 return;
2723
Douglas Gregor27381f32009-11-23 12:27:39 +00002724 // Overload resolution is always an unevaluated context.
2725 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2726
Douglas Gregorab7897a2008-11-19 22:57:39 +00002727 CandidateSet.push_back(OverloadCandidate());
2728 OverloadCandidate& Candidate = CandidateSet.back();
2729 Candidate.Function = 0;
2730 Candidate.Surrogate = Conversion;
2731 Candidate.Viable = true;
2732 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002733 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002734 Candidate.Conversions.resize(NumArgs + 1);
2735
2736 // Determine the implicit conversion sequence for the implicit
2737 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002738 ImplicitConversionSequence ObjectInit
Douglas Gregorab7897a2008-11-19 22:57:39 +00002739 = TryObjectArgumentInitialization(Object, Conversion);
2740 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2741 Candidate.Viable = false;
2742 return;
2743 }
2744
2745 // The first conversion is actually a user-defined conversion whose
2746 // first conversion is ObjectInit's standard conversion (which is
2747 // effectively a reference binding). Record it as such.
Mike Stump11289f42009-09-09 15:08:12 +00002748 Candidate.Conversions[0].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002749 = ImplicitConversionSequence::UserDefinedConversion;
2750 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002751 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002752 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002753 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002754 = Candidate.Conversions[0].UserDefined.Before;
2755 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2756
Mike Stump11289f42009-09-09 15:08:12 +00002757 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002758 unsigned NumArgsInProto = Proto->getNumArgs();
2759
2760 // (C++ 13.3.2p2): A candidate function having fewer than m
2761 // parameters is viable only if it has an ellipsis in its parameter
2762 // list (8.3.5).
2763 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2764 Candidate.Viable = false;
2765 return;
2766 }
2767
2768 // Function types don't have any default arguments, so just check if
2769 // we have enough arguments.
2770 if (NumArgs < NumArgsInProto) {
2771 // Not enough arguments.
2772 Candidate.Viable = false;
2773 return;
2774 }
2775
2776 // Determine the implicit conversion sequences for each of the
2777 // arguments.
2778 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2779 if (ArgIdx < NumArgsInProto) {
2780 // (C++ 13.3.2p3): for F to be a viable function, there shall
2781 // exist for each argument an implicit conversion sequence
2782 // (13.3.3.1) that converts that argument to the corresponding
2783 // parameter of F.
2784 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002785 Candidate.Conversions[ArgIdx + 1]
2786 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002787 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002788 /*ForceRValue=*/false,
2789 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002790 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002791 == ImplicitConversionSequence::BadConversion) {
2792 Candidate.Viable = false;
2793 break;
2794 }
2795 } else {
2796 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2797 // argument for which there is no corresponding parameter is
2798 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002799 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002800 = ImplicitConversionSequence::EllipsisConversion;
2801 }
2802 }
2803}
2804
Mike Stump87c57ac2009-05-16 07:39:55 +00002805// FIXME: This will eventually be removed, once we've migrated all of the
2806// operator overloading logic over to the scheme used by binary operators, which
2807// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002808void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002809 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002810 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002811 OverloadCandidateSet& CandidateSet,
2812 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002813 FunctionSet Functions;
2814
2815 QualType T1 = Args[0]->getType();
2816 QualType T2;
2817 if (NumArgs > 1)
2818 T2 = Args[1]->getType();
2819
2820 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002821 if (S)
2822 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redlc057f422009-10-23 19:23:15 +00002823 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002824 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2825 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002826 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002827}
2828
2829/// \brief Add overload candidates for overloaded operators that are
2830/// member functions.
2831///
2832/// Add the overloaded operator candidates that are member functions
2833/// for the operator Op that was used in an operator expression such
2834/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2835/// CandidateSet will store the added overload candidates. (C++
2836/// [over.match.oper]).
2837void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2838 SourceLocation OpLoc,
2839 Expr **Args, unsigned NumArgs,
2840 OverloadCandidateSet& CandidateSet,
2841 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002842 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2843
2844 // C++ [over.match.oper]p3:
2845 // For a unary operator @ with an operand of a type whose
2846 // cv-unqualified version is T1, and for a binary operator @ with
2847 // a left operand of a type whose cv-unqualified version is T1 and
2848 // a right operand of a type whose cv-unqualified version is T2,
2849 // three sets of candidate functions, designated member
2850 // candidates, non-member candidates and built-in candidates, are
2851 // constructed as follows:
2852 QualType T1 = Args[0]->getType();
2853 QualType T2;
2854 if (NumArgs > 1)
2855 T2 = Args[1]->getType();
2856
2857 // -- If T1 is a class type, the set of member candidates is the
2858 // result of the qualified lookup of T1::operator@
2859 // (13.3.1.1.1); otherwise, the set of member candidates is
2860 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002861 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002862 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00002863 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002864 return;
Mike Stump11289f42009-09-09 15:08:12 +00002865
John McCall27b18f82009-11-17 02:14:36 +00002866 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
2867 LookupQualifiedName(Operators, T1Rec->getDecl());
2868 Operators.suppressDiagnostics();
2869
Mike Stump11289f42009-09-09 15:08:12 +00002870 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002871 OperEnd = Operators.end();
2872 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00002873 ++Oper)
2874 AddMethodCandidate(*Oper, Args[0], Args + 1, NumArgs - 1, CandidateSet,
2875 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00002876 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002877}
2878
Douglas Gregora11693b2008-11-12 17:17:38 +00002879/// AddBuiltinCandidate - Add a candidate for a built-in
2880/// operator. ResultTy and ParamTys are the result and parameter types
2881/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00002882/// arguments being passed to the candidate. IsAssignmentOperator
2883/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00002884/// operator. NumContextualBoolArguments is the number of arguments
2885/// (at the beginning of the argument list) that will be contextually
2886/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00002887void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00002888 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00002889 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002890 bool IsAssignmentOperator,
2891 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00002892 // Overload resolution is always an unevaluated context.
2893 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2894
Douglas Gregora11693b2008-11-12 17:17:38 +00002895 // Add this candidate
2896 CandidateSet.push_back(OverloadCandidate());
2897 OverloadCandidate& Candidate = CandidateSet.back();
2898 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00002899 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002900 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00002901 Candidate.BuiltinTypes.ResultTy = ResultTy;
2902 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2903 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2904
2905 // Determine the implicit conversion sequences for each of the
2906 // arguments.
2907 Candidate.Viable = true;
2908 Candidate.Conversions.resize(NumArgs);
2909 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00002910 // C++ [over.match.oper]p4:
2911 // For the built-in assignment operators, conversions of the
2912 // left operand are restricted as follows:
2913 // -- no temporaries are introduced to hold the left operand, and
2914 // -- no user-defined conversions are applied to the left
2915 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00002916 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00002917 //
2918 // We block these conversions by turning off user-defined
2919 // conversions, since that is the only way that initialization of
2920 // a reference to a non-class type can occur from something that
2921 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002922 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00002923 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00002924 "Contextual conversion to bool requires bool type");
2925 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2926 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002927 Candidate.Conversions[ArgIdx]
2928 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00002929 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00002930 /*ForceRValue=*/false,
2931 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002932 }
Mike Stump11289f42009-09-09 15:08:12 +00002933 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002934 == ImplicitConversionSequence::BadConversion) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002935 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002936 break;
2937 }
Douglas Gregora11693b2008-11-12 17:17:38 +00002938 }
2939}
2940
2941/// BuiltinCandidateTypeSet - A set of types that will be used for the
2942/// candidate operator functions for built-in operators (C++
2943/// [over.built]). The types are separated into pointer types and
2944/// enumeration types.
2945class BuiltinCandidateTypeSet {
2946 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002947 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00002948
2949 /// PointerTypes - The set of pointer types that will be used in the
2950 /// built-in candidates.
2951 TypeSet PointerTypes;
2952
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002953 /// MemberPointerTypes - The set of member pointer types that will be
2954 /// used in the built-in candidates.
2955 TypeSet MemberPointerTypes;
2956
Douglas Gregora11693b2008-11-12 17:17:38 +00002957 /// EnumerationTypes - The set of enumeration types that will be
2958 /// used in the built-in candidates.
2959 TypeSet EnumerationTypes;
2960
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002961 /// Sema - The semantic analysis instance where we are building the
2962 /// candidate type set.
2963 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00002964
Douglas Gregora11693b2008-11-12 17:17:38 +00002965 /// Context - The AST context in which we will build the type sets.
2966 ASTContext &Context;
2967
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00002968 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
2969 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002970 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002971
2972public:
2973 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002974 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00002975
Mike Stump11289f42009-09-09 15:08:12 +00002976 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002977 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00002978
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002979 void AddTypesConvertedFrom(QualType Ty,
2980 SourceLocation Loc,
2981 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00002982 bool AllowExplicitConversions,
2983 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00002984
2985 /// pointer_begin - First pointer type found;
2986 iterator pointer_begin() { return PointerTypes.begin(); }
2987
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002988 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002989 iterator pointer_end() { return PointerTypes.end(); }
2990
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002991 /// member_pointer_begin - First member pointer type found;
2992 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2993
2994 /// member_pointer_end - Past the last member pointer type found;
2995 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2996
Douglas Gregora11693b2008-11-12 17:17:38 +00002997 /// enumeration_begin - First enumeration type found;
2998 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2999
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003000 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003001 iterator enumeration_end() { return EnumerationTypes.end(); }
3002};
3003
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003004/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003005/// the set of pointer types along with any more-qualified variants of
3006/// that type. For example, if @p Ty is "int const *", this routine
3007/// will add "int const *", "int const volatile *", "int const
3008/// restrict *", and "int const volatile restrict *" to the set of
3009/// pointer types. Returns true if the add of @p Ty itself succeeded,
3010/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003011///
3012/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003013bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003014BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3015 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003016
Douglas Gregora11693b2008-11-12 17:17:38 +00003017 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003018 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003019 return false;
3020
John McCall8ccfcb52009-09-24 19:53:00 +00003021 const PointerType *PointerTy = Ty->getAs<PointerType>();
3022 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003023
John McCall8ccfcb52009-09-24 19:53:00 +00003024 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003025 // Don't add qualified variants of arrays. For one, they're not allowed
3026 // (the qualifier would sink to the element type), and for another, the
3027 // only overload situation where it matters is subscript or pointer +- int,
3028 // and those shouldn't have qualifier variants anyway.
3029 if (PointeeTy->isArrayType())
3030 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003031 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003032 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003033 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003034 bool hasVolatile = VisibleQuals.hasVolatile();
3035 bool hasRestrict = VisibleQuals.hasRestrict();
3036
John McCall8ccfcb52009-09-24 19:53:00 +00003037 // Iterate through all strict supersets of BaseCVR.
3038 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3039 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003040 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3041 // in the types.
3042 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3043 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003044 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3045 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003046 }
3047
3048 return true;
3049}
3050
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003051/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3052/// to the set of pointer types along with any more-qualified variants of
3053/// that type. For example, if @p Ty is "int const *", this routine
3054/// will add "int const *", "int const volatile *", "int const
3055/// restrict *", and "int const volatile restrict *" to the set of
3056/// pointer types. Returns true if the add of @p Ty itself succeeded,
3057/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003058///
3059/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003060bool
3061BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3062 QualType Ty) {
3063 // Insert this type.
3064 if (!MemberPointerTypes.insert(Ty))
3065 return false;
3066
John McCall8ccfcb52009-09-24 19:53:00 +00003067 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3068 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003069
John McCall8ccfcb52009-09-24 19:53:00 +00003070 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003071 // Don't add qualified variants of arrays. For one, they're not allowed
3072 // (the qualifier would sink to the element type), and for another, the
3073 // only overload situation where it matters is subscript or pointer +- int,
3074 // and those shouldn't have qualifier variants anyway.
3075 if (PointeeTy->isArrayType())
3076 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003077 const Type *ClassTy = PointerTy->getClass();
3078
3079 // Iterate through all strict supersets of the pointee type's CVR
3080 // qualifiers.
3081 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3082 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3083 if ((CVR | BaseCVR) != CVR) continue;
3084
3085 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3086 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003087 }
3088
3089 return true;
3090}
3091
Douglas Gregora11693b2008-11-12 17:17:38 +00003092/// AddTypesConvertedFrom - Add each of the types to which the type @p
3093/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003094/// primarily interested in pointer types and enumeration types. We also
3095/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003096/// AllowUserConversions is true if we should look at the conversion
3097/// functions of a class type, and AllowExplicitConversions if we
3098/// should also include the explicit conversion functions of a class
3099/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003100void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003101BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003102 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003103 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003104 bool AllowExplicitConversions,
3105 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003106 // Only deal with canonical types.
3107 Ty = Context.getCanonicalType(Ty);
3108
3109 // Look through reference types; they aren't part of the type of an
3110 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003111 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003112 Ty = RefTy->getPointeeType();
3113
3114 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003115 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003116
Sebastian Redl65ae2002009-11-05 16:36:20 +00003117 // If we're dealing with an array type, decay to the pointer.
3118 if (Ty->isArrayType())
3119 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3120
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003121 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003122 QualType PointeeTy = PointerTy->getPointeeType();
3123
3124 // Insert our type, and its more-qualified variants, into the set
3125 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003126 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003127 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003128 } else if (Ty->isMemberPointerType()) {
3129 // Member pointers are far easier, since the pointee can't be converted.
3130 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3131 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003132 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003133 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003134 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003135 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003136 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003137 // No conversion functions in incomplete types.
3138 return;
3139 }
Mike Stump11289f42009-09-09 15:08:12 +00003140
Douglas Gregora11693b2008-11-12 17:17:38 +00003141 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalld14a8642009-11-21 08:51:07 +00003142 const UnresolvedSet *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003143 = ClassDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00003144 for (UnresolvedSet::iterator I = Conversions->begin(),
3145 E = Conversions->end(); I != E; ++I) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003146
Mike Stump11289f42009-09-09 15:08:12 +00003147 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003148 // about which builtin types we can convert to.
John McCalld14a8642009-11-21 08:51:07 +00003149 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor05155d82009-08-21 23:19:43 +00003150 continue;
3151
John McCalld14a8642009-11-21 08:51:07 +00003152 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003153 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003154 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003155 VisibleQuals);
3156 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003157 }
3158 }
3159 }
3160}
3161
Douglas Gregor84605ae2009-08-24 13:43:27 +00003162/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3163/// the volatile- and non-volatile-qualified assignment operators for the
3164/// given type to the candidate set.
3165static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3166 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003167 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003168 unsigned NumArgs,
3169 OverloadCandidateSet &CandidateSet) {
3170 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003171
Douglas Gregor84605ae2009-08-24 13:43:27 +00003172 // T& operator=(T&, T)
3173 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3174 ParamTypes[1] = T;
3175 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3176 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003177
Douglas Gregor84605ae2009-08-24 13:43:27 +00003178 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3179 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003180 ParamTypes[0]
3181 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003182 ParamTypes[1] = T;
3183 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003184 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003185 }
3186}
Mike Stump11289f42009-09-09 15:08:12 +00003187
Sebastian Redl1054fae2009-10-25 17:03:50 +00003188/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3189/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003190static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3191 Qualifiers VRQuals;
3192 const RecordType *TyRec;
3193 if (const MemberPointerType *RHSMPType =
3194 ArgExpr->getType()->getAs<MemberPointerType>())
3195 TyRec = cast<RecordType>(RHSMPType->getClass());
3196 else
3197 TyRec = ArgExpr->getType()->getAs<RecordType>();
3198 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003199 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003200 VRQuals.addVolatile();
3201 VRQuals.addRestrict();
3202 return VRQuals;
3203 }
3204
3205 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalld14a8642009-11-21 08:51:07 +00003206 const UnresolvedSet *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003207 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003208
John McCalld14a8642009-11-21 08:51:07 +00003209 for (UnresolvedSet::iterator I = Conversions->begin(),
3210 E = Conversions->end(); I != E; ++I) {
3211 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003212 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3213 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3214 CanTy = ResTypeRef->getPointeeType();
3215 // Need to go down the pointer/mempointer chain and add qualifiers
3216 // as see them.
3217 bool done = false;
3218 while (!done) {
3219 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3220 CanTy = ResTypePtr->getPointeeType();
3221 else if (const MemberPointerType *ResTypeMPtr =
3222 CanTy->getAs<MemberPointerType>())
3223 CanTy = ResTypeMPtr->getPointeeType();
3224 else
3225 done = true;
3226 if (CanTy.isVolatileQualified())
3227 VRQuals.addVolatile();
3228 if (CanTy.isRestrictQualified())
3229 VRQuals.addRestrict();
3230 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3231 return VRQuals;
3232 }
3233 }
3234 }
3235 return VRQuals;
3236}
3237
Douglas Gregord08452f2008-11-19 15:42:04 +00003238/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3239/// operator overloads to the candidate set (C++ [over.built]), based
3240/// on the operator @p Op and the arguments given. For example, if the
3241/// operator is a binary '+', this routine might add "int
3242/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003243void
Mike Stump11289f42009-09-09 15:08:12 +00003244Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003245 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003246 Expr **Args, unsigned NumArgs,
3247 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003248 // The set of "promoted arithmetic types", which are the arithmetic
3249 // types are that preserved by promotion (C++ [over.built]p2). Note
3250 // that the first few of these types are the promoted integral
3251 // types; these types need to be first.
3252 // FIXME: What about complex?
3253 const unsigned FirstIntegralType = 0;
3254 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003255 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003256 LastPromotedIntegralType = 13;
3257 const unsigned FirstPromotedArithmeticType = 7,
3258 LastPromotedArithmeticType = 16;
3259 const unsigned NumArithmeticTypes = 16;
3260 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003261 Context.BoolTy, Context.CharTy, Context.WCharTy,
3262// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003263 Context.SignedCharTy, Context.ShortTy,
3264 Context.UnsignedCharTy, Context.UnsignedShortTy,
3265 Context.IntTy, Context.LongTy, Context.LongLongTy,
3266 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3267 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3268 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003269 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3270 "Invalid first promoted integral type");
3271 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3272 == Context.UnsignedLongLongTy &&
3273 "Invalid last promoted integral type");
3274 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3275 "Invalid first promoted arithmetic type");
3276 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3277 == Context.LongDoubleTy &&
3278 "Invalid last promoted arithmetic type");
3279
Douglas Gregora11693b2008-11-12 17:17:38 +00003280 // Find all of the types that the arguments can convert to, but only
3281 // if the operator we're looking at has built-in operator candidates
3282 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003283 Qualifiers VisibleTypeConversionsQuals;
3284 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003285 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3286 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3287
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003288 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003289 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3290 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003291 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003292 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003293 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003294 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003295 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003296 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003297 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003298 true,
3299 (Op == OO_Exclaim ||
3300 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003301 Op == OO_PipePipe),
3302 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003303 }
3304
3305 bool isComparison = false;
3306 switch (Op) {
3307 case OO_None:
3308 case NUM_OVERLOADED_OPERATORS:
3309 assert(false && "Expected an overloaded operator");
3310 break;
3311
Douglas Gregord08452f2008-11-19 15:42:04 +00003312 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003313 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003314 goto UnaryStar;
3315 else
3316 goto BinaryStar;
3317 break;
3318
3319 case OO_Plus: // '+' is either unary or binary
3320 if (NumArgs == 1)
3321 goto UnaryPlus;
3322 else
3323 goto BinaryPlus;
3324 break;
3325
3326 case OO_Minus: // '-' is either unary or binary
3327 if (NumArgs == 1)
3328 goto UnaryMinus;
3329 else
3330 goto BinaryMinus;
3331 break;
3332
3333 case OO_Amp: // '&' is either unary or binary
3334 if (NumArgs == 1)
3335 goto UnaryAmp;
3336 else
3337 goto BinaryAmp;
3338
3339 case OO_PlusPlus:
3340 case OO_MinusMinus:
3341 // C++ [over.built]p3:
3342 //
3343 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3344 // is either volatile or empty, there exist candidate operator
3345 // functions of the form
3346 //
3347 // VQ T& operator++(VQ T&);
3348 // T operator++(VQ T&, int);
3349 //
3350 // C++ [over.built]p4:
3351 //
3352 // For every pair (T, VQ), where T is an arithmetic type other
3353 // than bool, and VQ is either volatile or empty, there exist
3354 // candidate operator functions of the form
3355 //
3356 // VQ T& operator--(VQ T&);
3357 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003358 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003359 Arith < NumArithmeticTypes; ++Arith) {
3360 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003361 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003362 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003363
3364 // Non-volatile version.
3365 if (NumArgs == 1)
3366 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3367 else
3368 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003369 // heuristic to reduce number of builtin candidates in the set.
3370 // Add volatile version only if there are conversions to a volatile type.
3371 if (VisibleTypeConversionsQuals.hasVolatile()) {
3372 // Volatile version
3373 ParamTypes[0]
3374 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3375 if (NumArgs == 1)
3376 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3377 else
3378 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3379 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003380 }
3381
3382 // C++ [over.built]p5:
3383 //
3384 // For every pair (T, VQ), where T is a cv-qualified or
3385 // cv-unqualified object type, and VQ is either volatile or
3386 // empty, there exist candidate operator functions of the form
3387 //
3388 // T*VQ& operator++(T*VQ&);
3389 // T*VQ& operator--(T*VQ&);
3390 // T* operator++(T*VQ&, int);
3391 // T* operator--(T*VQ&, int);
3392 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3393 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3394 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003395 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003396 continue;
3397
Mike Stump11289f42009-09-09 15:08:12 +00003398 QualType ParamTypes[2] = {
3399 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003400 };
Mike Stump11289f42009-09-09 15:08:12 +00003401
Douglas Gregord08452f2008-11-19 15:42:04 +00003402 // Without volatile
3403 if (NumArgs == 1)
3404 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3405 else
3406 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3407
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003408 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3409 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003410 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003411 ParamTypes[0]
3412 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003413 if (NumArgs == 1)
3414 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3415 else
3416 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3417 }
3418 }
3419 break;
3420
3421 UnaryStar:
3422 // C++ [over.built]p6:
3423 // For every cv-qualified or cv-unqualified object type T, there
3424 // exist candidate operator functions of the form
3425 //
3426 // T& operator*(T*);
3427 //
3428 // C++ [over.built]p7:
3429 // For every function type T, there exist candidate operator
3430 // functions of the form
3431 // T& operator*(T*);
3432 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3433 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3434 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003435 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003436 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003437 &ParamTy, Args, 1, CandidateSet);
3438 }
3439 break;
3440
3441 UnaryPlus:
3442 // C++ [over.built]p8:
3443 // For every type T, there exist candidate operator functions of
3444 // the form
3445 //
3446 // T* operator+(T*);
3447 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3448 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3449 QualType ParamTy = *Ptr;
3450 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3451 }
Mike Stump11289f42009-09-09 15:08:12 +00003452
Douglas Gregord08452f2008-11-19 15:42:04 +00003453 // Fall through
3454
3455 UnaryMinus:
3456 // C++ [over.built]p9:
3457 // For every promoted arithmetic type T, there exist candidate
3458 // operator functions of the form
3459 //
3460 // T operator+(T);
3461 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003462 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003463 Arith < LastPromotedArithmeticType; ++Arith) {
3464 QualType ArithTy = ArithmeticTypes[Arith];
3465 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3466 }
3467 break;
3468
3469 case OO_Tilde:
3470 // C++ [over.built]p10:
3471 // For every promoted integral type T, there exist candidate
3472 // operator functions of the form
3473 //
3474 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003475 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003476 Int < LastPromotedIntegralType; ++Int) {
3477 QualType IntTy = ArithmeticTypes[Int];
3478 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3479 }
3480 break;
3481
Douglas Gregora11693b2008-11-12 17:17:38 +00003482 case OO_New:
3483 case OO_Delete:
3484 case OO_Array_New:
3485 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003486 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003487 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003488 break;
3489
3490 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003491 UnaryAmp:
3492 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003493 // C++ [over.match.oper]p3:
3494 // -- For the operator ',', the unary operator '&', or the
3495 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003496 break;
3497
Douglas Gregor84605ae2009-08-24 13:43:27 +00003498 case OO_EqualEqual:
3499 case OO_ExclaimEqual:
3500 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003501 // For every pointer to member type T, there exist candidate operator
3502 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003503 //
3504 // bool operator==(T,T);
3505 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003506 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003507 MemPtr = CandidateTypes.member_pointer_begin(),
3508 MemPtrEnd = CandidateTypes.member_pointer_end();
3509 MemPtr != MemPtrEnd;
3510 ++MemPtr) {
3511 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3512 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3513 }
Mike Stump11289f42009-09-09 15:08:12 +00003514
Douglas Gregor84605ae2009-08-24 13:43:27 +00003515 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003516
Douglas Gregora11693b2008-11-12 17:17:38 +00003517 case OO_Less:
3518 case OO_Greater:
3519 case OO_LessEqual:
3520 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003521 // C++ [over.built]p15:
3522 //
3523 // For every pointer or enumeration type T, there exist
3524 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003525 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003526 // bool operator<(T, T);
3527 // bool operator>(T, T);
3528 // bool operator<=(T, T);
3529 // bool operator>=(T, T);
3530 // bool operator==(T, T);
3531 // bool operator!=(T, T);
3532 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3533 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3534 QualType ParamTypes[2] = { *Ptr, *Ptr };
3535 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3536 }
Mike Stump11289f42009-09-09 15:08:12 +00003537 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003538 = CandidateTypes.enumeration_begin();
3539 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3540 QualType ParamTypes[2] = { *Enum, *Enum };
3541 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3542 }
3543
3544 // Fall through.
3545 isComparison = true;
3546
Douglas Gregord08452f2008-11-19 15:42:04 +00003547 BinaryPlus:
3548 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003549 if (!isComparison) {
3550 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3551
3552 // C++ [over.built]p13:
3553 //
3554 // For every cv-qualified or cv-unqualified object type T
3555 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003556 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003557 // T* operator+(T*, ptrdiff_t);
3558 // T& operator[](T*, ptrdiff_t); [BELOW]
3559 // T* operator-(T*, ptrdiff_t);
3560 // T* operator+(ptrdiff_t, T*);
3561 // T& operator[](ptrdiff_t, T*); [BELOW]
3562 //
3563 // C++ [over.built]p14:
3564 //
3565 // For every T, where T is a pointer to object type, there
3566 // exist candidate operator functions of the form
3567 //
3568 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003569 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003570 = CandidateTypes.pointer_begin();
3571 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3572 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3573
3574 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3575 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3576
3577 if (Op == OO_Plus) {
3578 // T* operator+(ptrdiff_t, T*);
3579 ParamTypes[0] = ParamTypes[1];
3580 ParamTypes[1] = *Ptr;
3581 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3582 } else {
3583 // ptrdiff_t operator-(T, T);
3584 ParamTypes[1] = *Ptr;
3585 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3586 Args, 2, CandidateSet);
3587 }
3588 }
3589 }
3590 // Fall through
3591
Douglas Gregora11693b2008-11-12 17:17:38 +00003592 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003593 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003594 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003595 // C++ [over.built]p12:
3596 //
3597 // For every pair of promoted arithmetic types L and R, there
3598 // exist candidate operator functions of the form
3599 //
3600 // LR operator*(L, R);
3601 // LR operator/(L, R);
3602 // LR operator+(L, R);
3603 // LR operator-(L, R);
3604 // bool operator<(L, R);
3605 // bool operator>(L, R);
3606 // bool operator<=(L, R);
3607 // bool operator>=(L, R);
3608 // bool operator==(L, R);
3609 // bool operator!=(L, R);
3610 //
3611 // where LR is the result of the usual arithmetic conversions
3612 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003613 //
3614 // C++ [over.built]p24:
3615 //
3616 // For every pair of promoted arithmetic types L and R, there exist
3617 // candidate operator functions of the form
3618 //
3619 // LR operator?(bool, L, R);
3620 //
3621 // where LR is the result of the usual arithmetic conversions
3622 // between types L and R.
3623 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003624 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003625 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003626 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003627 Right < LastPromotedArithmeticType; ++Right) {
3628 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003629 QualType Result
3630 = isComparison
3631 ? Context.BoolTy
3632 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003633 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3634 }
3635 }
3636 break;
3637
3638 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003639 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003640 case OO_Caret:
3641 case OO_Pipe:
3642 case OO_LessLess:
3643 case OO_GreaterGreater:
3644 // C++ [over.built]p17:
3645 //
3646 // For every pair of promoted integral types L and R, there
3647 // exist candidate operator functions of the form
3648 //
3649 // LR operator%(L, R);
3650 // LR operator&(L, R);
3651 // LR operator^(L, R);
3652 // LR operator|(L, R);
3653 // L operator<<(L, R);
3654 // L operator>>(L, R);
3655 //
3656 // where LR is the result of the usual arithmetic conversions
3657 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003658 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003659 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003660 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003661 Right < LastPromotedIntegralType; ++Right) {
3662 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3663 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3664 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003665 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003666 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3667 }
3668 }
3669 break;
3670
3671 case OO_Equal:
3672 // C++ [over.built]p20:
3673 //
3674 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003675 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003676 // empty, there exist candidate operator functions of the form
3677 //
3678 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003679 for (BuiltinCandidateTypeSet::iterator
3680 Enum = CandidateTypes.enumeration_begin(),
3681 EnumEnd = CandidateTypes.enumeration_end();
3682 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003683 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003684 CandidateSet);
3685 for (BuiltinCandidateTypeSet::iterator
3686 MemPtr = CandidateTypes.member_pointer_begin(),
3687 MemPtrEnd = CandidateTypes.member_pointer_end();
3688 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003689 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003690 CandidateSet);
3691 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003692
3693 case OO_PlusEqual:
3694 case OO_MinusEqual:
3695 // C++ [over.built]p19:
3696 //
3697 // For every pair (T, VQ), where T is any type and VQ is either
3698 // volatile or empty, there exist candidate operator functions
3699 // of the form
3700 //
3701 // T*VQ& operator=(T*VQ&, T*);
3702 //
3703 // C++ [over.built]p21:
3704 //
3705 // For every pair (T, VQ), where T is a cv-qualified or
3706 // cv-unqualified object type and VQ is either volatile or
3707 // empty, there exist candidate operator functions of the form
3708 //
3709 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3710 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3711 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3712 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3713 QualType ParamTypes[2];
3714 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3715
3716 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003717 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003718 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3719 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003720
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003721 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3722 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003723 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003724 ParamTypes[0]
3725 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003726 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3727 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003728 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003729 }
3730 // Fall through.
3731
3732 case OO_StarEqual:
3733 case OO_SlashEqual:
3734 // C++ [over.built]p18:
3735 //
3736 // For every triple (L, VQ, R), where L is an arithmetic type,
3737 // VQ is either volatile or empty, and R is a promoted
3738 // arithmetic type, there exist candidate operator functions of
3739 // the form
3740 //
3741 // VQ L& operator=(VQ L&, R);
3742 // VQ L& operator*=(VQ L&, R);
3743 // VQ L& operator/=(VQ L&, R);
3744 // VQ L& operator+=(VQ L&, R);
3745 // VQ L& operator-=(VQ L&, R);
3746 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003747 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003748 Right < LastPromotedArithmeticType; ++Right) {
3749 QualType ParamTypes[2];
3750 ParamTypes[1] = ArithmeticTypes[Right];
3751
3752 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003753 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003754 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3755 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003756
3757 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003758 if (VisibleTypeConversionsQuals.hasVolatile()) {
3759 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3760 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3761 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3762 /*IsAssigmentOperator=*/Op == OO_Equal);
3763 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003764 }
3765 }
3766 break;
3767
3768 case OO_PercentEqual:
3769 case OO_LessLessEqual:
3770 case OO_GreaterGreaterEqual:
3771 case OO_AmpEqual:
3772 case OO_CaretEqual:
3773 case OO_PipeEqual:
3774 // C++ [over.built]p22:
3775 //
3776 // For every triple (L, VQ, R), where L is an integral type, VQ
3777 // is either volatile or empty, and R is a promoted integral
3778 // type, there exist candidate operator functions of the form
3779 //
3780 // VQ L& operator%=(VQ L&, R);
3781 // VQ L& operator<<=(VQ L&, R);
3782 // VQ L& operator>>=(VQ L&, R);
3783 // VQ L& operator&=(VQ L&, R);
3784 // VQ L& operator^=(VQ L&, R);
3785 // VQ L& operator|=(VQ L&, R);
3786 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003787 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003788 Right < LastPromotedIntegralType; ++Right) {
3789 QualType ParamTypes[2];
3790 ParamTypes[1] = ArithmeticTypes[Right];
3791
3792 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003793 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003794 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00003795 if (VisibleTypeConversionsQuals.hasVolatile()) {
3796 // Add this built-in operator as a candidate (VQ is 'volatile').
3797 ParamTypes[0] = ArithmeticTypes[Left];
3798 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3799 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3800 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3801 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003802 }
3803 }
3804 break;
3805
Douglas Gregord08452f2008-11-19 15:42:04 +00003806 case OO_Exclaim: {
3807 // C++ [over.operator]p23:
3808 //
3809 // There also exist candidate operator functions of the form
3810 //
Mike Stump11289f42009-09-09 15:08:12 +00003811 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003812 // bool operator&&(bool, bool); [BELOW]
3813 // bool operator||(bool, bool); [BELOW]
3814 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003815 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3816 /*IsAssignmentOperator=*/false,
3817 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003818 break;
3819 }
3820
Douglas Gregora11693b2008-11-12 17:17:38 +00003821 case OO_AmpAmp:
3822 case OO_PipePipe: {
3823 // C++ [over.operator]p23:
3824 //
3825 // There also exist candidate operator functions of the form
3826 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003827 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003828 // bool operator&&(bool, bool);
3829 // bool operator||(bool, bool);
3830 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003831 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3832 /*IsAssignmentOperator=*/false,
3833 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003834 break;
3835 }
3836
3837 case OO_Subscript:
3838 // C++ [over.built]p13:
3839 //
3840 // For every cv-qualified or cv-unqualified object type T there
3841 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003842 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003843 // T* operator+(T*, ptrdiff_t); [ABOVE]
3844 // T& operator[](T*, ptrdiff_t);
3845 // T* operator-(T*, ptrdiff_t); [ABOVE]
3846 // T* operator+(ptrdiff_t, T*); [ABOVE]
3847 // T& operator[](ptrdiff_t, T*);
3848 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3849 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3850 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003851 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003852 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003853
3854 // T& operator[](T*, ptrdiff_t)
3855 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3856
3857 // T& operator[](ptrdiff_t, T*);
3858 ParamTypes[0] = ParamTypes[1];
3859 ParamTypes[1] = *Ptr;
3860 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3861 }
3862 break;
3863
3864 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003865 // C++ [over.built]p11:
3866 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3867 // C1 is the same type as C2 or is a derived class of C2, T is an object
3868 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3869 // there exist candidate operator functions of the form
3870 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3871 // where CV12 is the union of CV1 and CV2.
3872 {
3873 for (BuiltinCandidateTypeSet::iterator Ptr =
3874 CandidateTypes.pointer_begin();
3875 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3876 QualType C1Ty = (*Ptr);
3877 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003878 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003879 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003880 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003881 if (!isa<RecordType>(C1))
3882 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003883 // heuristic to reduce number of builtin candidates in the set.
3884 // Add volatile/restrict version only if there are conversions to a
3885 // volatile/restrict type.
3886 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3887 continue;
3888 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3889 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003890 }
3891 for (BuiltinCandidateTypeSet::iterator
3892 MemPtr = CandidateTypes.member_pointer_begin(),
3893 MemPtrEnd = CandidateTypes.member_pointer_end();
3894 MemPtr != MemPtrEnd; ++MemPtr) {
3895 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3896 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00003897 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003898 if (C1 != C2 && !IsDerivedFrom(C1, C2))
3899 break;
3900 QualType ParamTypes[2] = { *Ptr, *MemPtr };
3901 // build CV12 T&
3902 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003903 if (!VisibleTypeConversionsQuals.hasVolatile() &&
3904 T.isVolatileQualified())
3905 continue;
3906 if (!VisibleTypeConversionsQuals.hasRestrict() &&
3907 T.isRestrictQualified())
3908 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003909 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003910 QualType ResultTy = Context.getLValueReferenceType(T);
3911 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3912 }
3913 }
3914 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003915 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003916
3917 case OO_Conditional:
3918 // Note that we don't consider the first argument, since it has been
3919 // contextually converted to bool long ago. The candidates below are
3920 // therefore added as binary.
3921 //
3922 // C++ [over.built]p24:
3923 // For every type T, where T is a pointer or pointer-to-member type,
3924 // there exist candidate operator functions of the form
3925 //
3926 // T operator?(bool, T, T);
3927 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00003928 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3929 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3930 QualType ParamTypes[2] = { *Ptr, *Ptr };
3931 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3932 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003933 for (BuiltinCandidateTypeSet::iterator Ptr =
3934 CandidateTypes.member_pointer_begin(),
3935 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3936 QualType ParamTypes[2] = { *Ptr, *Ptr };
3937 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3938 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003939 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00003940 }
3941}
3942
Douglas Gregore254f902009-02-04 00:32:51 +00003943/// \brief Add function candidates found via argument-dependent lookup
3944/// to the set of overloading candidates.
3945///
3946/// This routine performs argument-dependent name lookup based on the
3947/// given function name (which may also be an operator name) and adds
3948/// all of the overload candidates found by ADL to the overload
3949/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00003950void
Douglas Gregore254f902009-02-04 00:32:51 +00003951Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3952 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00003953 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00003954 OverloadCandidateSet& CandidateSet,
3955 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003956 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00003957
Douglas Gregorcabea402009-09-22 15:41:20 +00003958 // FIXME: Should we be trafficking in canonical function decls throughout?
3959
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003960 // Record all of the function candidates that we've already
3961 // added to the overload set, so that we don't add those same
3962 // candidates a second time.
3963 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3964 CandEnd = CandidateSet.end();
3965 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003966 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003967 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003968 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3969 Functions.insert(FunTmpl);
3970 }
Douglas Gregore254f902009-02-04 00:32:51 +00003971
Douglas Gregorcabea402009-09-22 15:41:20 +00003972 // FIXME: Pass in the explicit template arguments?
Sebastian Redlc057f422009-10-23 19:23:15 +00003973 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00003974
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003975 // Erase all of the candidates we already knew about.
3976 // FIXME: This is suboptimal. Is there a better way?
3977 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3978 CandEnd = CandidateSet.end();
3979 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003980 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003981 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003982 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3983 Functions.erase(FunTmpl);
3984 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003985
3986 // For each of the ADL candidates we found, add it to the overload
3987 // set.
3988 for (FunctionSet::iterator Func = Functions.begin(),
3989 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00003990 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003991 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
John McCall6b51f282009-11-23 01:53:49 +00003992 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00003993 continue;
3994
3995 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
3996 false, false, PartialOverloading);
3997 } else
Mike Stump11289f42009-09-09 15:08:12 +00003998 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00003999 ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004000 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004001 }
Douglas Gregore254f902009-02-04 00:32:51 +00004002}
4003
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004004/// isBetterOverloadCandidate - Determines whether the first overload
4005/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004006bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004007Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00004008 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004009 // Define viable functions to be better candidates than non-viable
4010 // functions.
4011 if (!Cand2.Viable)
4012 return Cand1.Viable;
4013 else if (!Cand1.Viable)
4014 return false;
4015
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004016 // C++ [over.match.best]p1:
4017 //
4018 // -- if F is a static member function, ICS1(F) is defined such
4019 // that ICS1(F) is neither better nor worse than ICS1(G) for
4020 // any function G, and, symmetrically, ICS1(G) is neither
4021 // better nor worse than ICS1(F).
4022 unsigned StartArg = 0;
4023 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4024 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004025
Douglas Gregord3cb3562009-07-07 23:38:56 +00004026 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004027 // A viable function F1 is defined to be a better function than another
4028 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004029 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004030 unsigned NumArgs = Cand1.Conversions.size();
4031 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4032 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004033 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004034 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4035 Cand2.Conversions[ArgIdx])) {
4036 case ImplicitConversionSequence::Better:
4037 // Cand1 has a better conversion sequence.
4038 HasBetterConversion = true;
4039 break;
4040
4041 case ImplicitConversionSequence::Worse:
4042 // Cand1 can't be better than Cand2.
4043 return false;
4044
4045 case ImplicitConversionSequence::Indistinguishable:
4046 // Do nothing.
4047 break;
4048 }
4049 }
4050
Mike Stump11289f42009-09-09 15:08:12 +00004051 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004052 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004053 if (HasBetterConversion)
4054 return true;
4055
Mike Stump11289f42009-09-09 15:08:12 +00004056 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004057 // specialization, or, if not that,
4058 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4059 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4060 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004061
4062 // -- F1 and F2 are function template specializations, and the function
4063 // template for F1 is more specialized than the template for F2
4064 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004065 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004066 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4067 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004068 if (FunctionTemplateDecl *BetterTemplate
4069 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4070 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00004071 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4072 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004073 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004074
Douglas Gregora1f013e2008-11-07 22:36:19 +00004075 // -- the context is an initialization by user-defined conversion
4076 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4077 // from the return type of F1 to the destination type (i.e.,
4078 // the type of the entity being initialized) is a better
4079 // conversion sequence than the standard conversion sequence
4080 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004081 if (Cand1.Function && Cand2.Function &&
4082 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004083 isa<CXXConversionDecl>(Cand2.Function)) {
4084 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4085 Cand2.FinalConversion)) {
4086 case ImplicitConversionSequence::Better:
4087 // Cand1 has a better conversion sequence.
4088 return true;
4089
4090 case ImplicitConversionSequence::Worse:
4091 // Cand1 can't be better than Cand2.
4092 return false;
4093
4094 case ImplicitConversionSequence::Indistinguishable:
4095 // Do nothing
4096 break;
4097 }
4098 }
4099
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004100 return false;
4101}
4102
Mike Stump11289f42009-09-09 15:08:12 +00004103/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004104/// within an overload candidate set.
4105///
4106/// \param CandidateSet the set of candidate functions.
4107///
4108/// \param Loc the location of the function name (or operator symbol) for
4109/// which overload resolution occurs.
4110///
Mike Stump11289f42009-09-09 15:08:12 +00004111/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004112/// function, Best points to the candidate function found.
4113///
4114/// \returns The result of overload resolution.
Mike Stump11289f42009-09-09 15:08:12 +00004115Sema::OverloadingResult
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004116Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004117 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004118 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004119 // Find the best viable function.
4120 Best = CandidateSet.end();
4121 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4122 Cand != CandidateSet.end(); ++Cand) {
4123 if (Cand->Viable) {
4124 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4125 Best = Cand;
4126 }
4127 }
4128
4129 // If we didn't find any viable functions, abort.
4130 if (Best == CandidateSet.end())
4131 return OR_No_Viable_Function;
4132
4133 // Make sure that this function is better than every other viable
4134 // function. If not, we have an ambiguity.
4135 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4136 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004137 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004138 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00004139 !isBetterOverloadCandidate(*Best, *Cand)) {
4140 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004141 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004142 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004143 }
Mike Stump11289f42009-09-09 15:08:12 +00004144
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004145 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004146 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004147 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004148 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004149 return OR_Deleted;
4150
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004151 // C++ [basic.def.odr]p2:
4152 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004153 // when referred to from a potentially-evaluated expression. [Note: this
4154 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004155 // (clause 13), user-defined conversions (12.3.2), allocation function for
4156 // placement new (5.3.4), as well as non-default initialization (8.5).
4157 if (Best->Function)
4158 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004159 return OR_Success;
4160}
4161
4162/// PrintOverloadCandidates - When overload resolution fails, prints
4163/// diagnostic messages containing the candidates in the candidate
4164/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump11289f42009-09-09 15:08:12 +00004165void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004166Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004167 bool OnlyViable,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004168 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004169 SourceLocation OpLoc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004170 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4171 LastCand = CandidateSet.end();
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004172 bool Reported = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004173 for (; Cand != LastCand; ++Cand) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004174 if (Cand->Viable || !OnlyViable) {
4175 if (Cand->Function) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004176 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004177 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004178 // Deleted or "unavailable" function.
4179 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4180 << Cand->Function->isDeleted();
Douglas Gregor4fb9cde8e2009-09-15 20:11:42 +00004181 } else if (FunctionTemplateDecl *FunTmpl
4182 = Cand->Function->getPrimaryTemplate()) {
4183 // Function template specialization
4184 // FIXME: Give a better reason!
4185 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4186 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4187 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor171c45a2009-02-18 21:56:37 +00004188 } else {
4189 // Normal function
Fariborz Jahanian21ccf062009-09-23 00:58:07 +00004190 bool errReported = false;
4191 if (!Cand->Viable && Cand->Conversions.size() > 0) {
4192 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4193 const ImplicitConversionSequence &Conversion =
4194 Cand->Conversions[i];
4195 if ((Conversion.ConversionKind !=
4196 ImplicitConversionSequence::BadConversion) ||
4197 Conversion.ConversionFunctionSet.size() == 0)
4198 continue;
4199 Diag(Cand->Function->getLocation(),
4200 diag::err_ovl_candidate_not_viable) << (i+1);
4201 errReported = true;
4202 for (int j = Conversion.ConversionFunctionSet.size()-1;
4203 j >= 0; j--) {
4204 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4205 Diag(Func->getLocation(), diag::err_ovl_candidate);
4206 }
4207 }
4208 }
4209 if (!errReported)
4210 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor171c45a2009-02-18 21:56:37 +00004211 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00004212 } else if (Cand->IsSurrogate) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004213 // Desugar the type of the surrogate down to a function type,
4214 // retaining as many typedefs as possible while still showing
4215 // the function type (and, therefore, its parameter types).
4216 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004217 bool isLValueReference = false;
4218 bool isRValueReference = false;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004219 bool isPointer = false;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004220 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004221 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004222 FnType = FnTypeRef->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004223 isLValueReference = true;
4224 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004225 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004226 FnType = FnTypeRef->getPointeeType();
4227 isRValueReference = true;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004228 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004229 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004230 FnType = FnTypePtr->getPointeeType();
4231 isPointer = true;
4232 }
4233 // Desugar down to a function type.
John McCall9dd450b2009-09-21 23:43:11 +00004234 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004235 // Reconstruct the pointer/reference as appropriate.
4236 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004237 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4238 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004239
Douglas Gregorab7897a2008-11-19 22:57:39 +00004240 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004241 << FnType;
Douglas Gregor66950a32009-09-30 21:46:01 +00004242 } else if (OnlyViable) {
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004243 assert(Cand->Conversions.size() <= 2 &&
Fariborz Jahanian0fe5e032009-10-09 17:09:58 +00004244 "builtin-binary-operator-not-binary");
Fariborz Jahanian956127d2009-10-16 23:25:02 +00004245 std::string TypeStr("operator");
4246 TypeStr += Opc;
4247 TypeStr += "(";
4248 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4249 if (Cand->Conversions.size() == 1) {
4250 TypeStr += ")";
4251 Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr;
4252 }
4253 else {
4254 TypeStr += ", ";
4255 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4256 TypeStr += ")";
4257 Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr;
4258 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004259 }
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004260 else if (!Cand->Viable && !Reported) {
4261 // Non-viability might be due to ambiguous user-defined conversions,
4262 // needed for built-in operators. Report them as well, but only once
4263 // as we have typically many built-in candidates.
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004264 unsigned NoOperands = Cand->Conversions.size();
4265 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004266 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4267 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4268 ICS.ConversionFunctionSet.empty())
4269 continue;
4270 if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4271 Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4272 QualType FromTy =
4273 QualType(
4274 static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4275 Diag(OpLoc,diag::note_ambiguous_type_conversion)
4276 << FromTy << Func->getConversionType();
4277 }
4278 for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4279 FunctionDecl *Func =
4280 Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4281 Diag(Func->getLocation(),diag::err_ovl_candidate);
4282 }
4283 }
4284 Reported = true;
4285 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004286 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004287 }
4288}
4289
Douglas Gregorcd695e52008-11-10 20:40:00 +00004290/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4291/// an overloaded function (C++ [over.over]), where @p From is an
4292/// expression with overloaded function type and @p ToType is the type
4293/// we're trying to resolve to. For example:
4294///
4295/// @code
4296/// int f(double);
4297/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004298///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004299/// int (*pfd)(double) = f; // selects f(double)
4300/// @endcode
4301///
4302/// This routine returns the resulting FunctionDecl if it could be
4303/// resolved, and NULL otherwise. When @p Complain is true, this
4304/// routine will emit diagnostics if there is an error.
4305FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004306Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004307 bool Complain) {
4308 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004309 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004310 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004311 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004312 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004313 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004314 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004315 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004316 FunctionType = MemTypePtr->getPointeeType();
4317 IsMember = true;
4318 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004319
4320 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00004321 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00004322 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004323 return 0;
4324
4325 // Find the actual overloaded function declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004326
Douglas Gregorcd695e52008-11-10 20:40:00 +00004327 // C++ [over.over]p1:
4328 // [...] [Note: any redundant set of parentheses surrounding the
4329 // overloaded function name is ignored (5.1). ]
4330 Expr *OvlExpr = From->IgnoreParens();
4331
4332 // C++ [over.over]p1:
4333 // [...] The overloaded function name can be preceded by the &
4334 // operator.
4335 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4336 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4337 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4338 }
4339
Anders Carlssonb68b0282009-10-20 22:53:47 +00004340 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004341 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCalld14a8642009-11-21 08:51:07 +00004342
4343 llvm::SmallVector<NamedDecl*,8> Fns;
Anders Carlssonb68b0282009-10-20 22:53:47 +00004344
Douglas Gregorcd695e52008-11-10 20:40:00 +00004345 // Try to dig out the overloaded function.
John McCalld14a8642009-11-21 08:51:07 +00004346 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregor9b146582009-07-08 20:55:45 +00004347 FunctionTemplateDecl *FunctionTemplate = 0;
4348 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
John McCalld14a8642009-11-21 08:51:07 +00004349 assert(!isa<OverloadedFunctionDecl>(DR->getDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004350 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
Douglas Gregord3319842009-10-24 04:59:53 +00004351 HasExplicitTemplateArgs = DR->hasExplicitTemplateArgumentList();
John McCall6b51f282009-11-23 01:53:49 +00004352 if (HasExplicitTemplateArgs)
4353 DR->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00004354 } else if (UnresolvedLookupExpr *UL
4355 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4356 Fns.append(UL->decls_begin(), UL->decls_end());
Anders Carlsson6c966c42009-10-07 22:26:29 +00004357 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(OvlExpr)) {
4358 Ovl = dyn_cast<OverloadedFunctionDecl>(ME->getMemberDecl());
4359 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(ME->getMemberDecl());
Douglas Gregord3319842009-10-24 04:59:53 +00004360 HasExplicitTemplateArgs = ME->hasExplicitTemplateArgumentList();
John McCall6b51f282009-11-23 01:53:49 +00004361 if (HasExplicitTemplateArgs)
4362 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Anders Carlssonb68b0282009-10-20 22:53:47 +00004363 } else if (TemplateIdRefExpr *TIRE = dyn_cast<TemplateIdRefExpr>(OvlExpr)) {
4364 TemplateName Name = TIRE->getTemplateName();
4365 Ovl = Name.getAsOverloadedFunctionDecl();
4366 FunctionTemplate =
4367 dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4368
4369 HasExplicitTemplateArgs = true;
John McCall6b51f282009-11-23 01:53:49 +00004370 TIRE->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Douglas Gregor9b146582009-07-08 20:55:45 +00004371 }
Mike Stump11289f42009-09-09 15:08:12 +00004372
John McCalld14a8642009-11-21 08:51:07 +00004373 if (Ovl) Fns.append(Ovl->function_begin(), Ovl->function_end());
4374 if (FunctionTemplate) Fns.push_back(FunctionTemplate);
4375
4376 // If we didn't actually find anything, we're done.
4377 if (Fns.empty())
4378 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004379
Douglas Gregorcd695e52008-11-10 20:40:00 +00004380 // Look through all of the overloaded functions, searching for one
4381 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004382 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004383 bool FoundNonTemplateFunction = false;
John McCalld14a8642009-11-21 08:51:07 +00004384 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4385 E = Fns.end(); I != E; ++I) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004386 // C++ [over.over]p3:
4387 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00004388 // targets of type "pointer-to-function" or "reference-to-function."
4389 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004390 // type "pointer-to-member-function."
4391 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004392
Mike Stump11289f42009-09-09 15:08:12 +00004393 if (FunctionTemplateDecl *FunctionTemplate
John McCalld14a8642009-11-21 08:51:07 +00004394 = dyn_cast<FunctionTemplateDecl>(*I)) {
Mike Stump11289f42009-09-09 15:08:12 +00004395 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004396 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004397 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004398 // static when converting to member pointer.
4399 if (Method->isStatic() == IsMember)
4400 continue;
4401 } else if (IsMember)
4402 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004403
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004404 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004405 // If the name is a function template, template argument deduction is
4406 // done (14.8.2.2), and if the argument deduction succeeds, the
4407 // resulting template argument list is used to generate a single
4408 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004409 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004410 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00004411 FunctionDecl *Specialization = 0;
4412 TemplateDeductionInfo Info(Context);
4413 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004414 = DeduceTemplateArguments(FunctionTemplate,
4415 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
Douglas Gregor9b146582009-07-08 20:55:45 +00004416 FunctionType, Specialization, Info)) {
4417 // FIXME: make a note of the failed deduction for diagnostics.
4418 (void)Result;
4419 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004420 // FIXME: If the match isn't exact, shouldn't we just drop this as
4421 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00004422 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004423 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004424 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004425 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004426 }
John McCalld14a8642009-11-21 08:51:07 +00004427
4428 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00004429 }
Mike Stump11289f42009-09-09 15:08:12 +00004430
John McCalld14a8642009-11-21 08:51:07 +00004431 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004432 // Skip non-static functions when converting to pointer, and static
4433 // when converting to member pointer.
4434 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004435 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00004436
4437 // If we have explicit template arguments, skip non-templates.
4438 if (HasExplicitTemplateArgs)
4439 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004440 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004441 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004442
John McCalld14a8642009-11-21 08:51:07 +00004443 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*I)) {
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004444 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
John McCalld14a8642009-11-21 08:51:07 +00004445 Matches.insert(cast<FunctionDecl>(FunDecl->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004446 FoundNonTemplateFunction = true;
4447 }
Mike Stump11289f42009-09-09 15:08:12 +00004448 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004449 }
4450
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004451 // If there were 0 or 1 matches, we're done.
4452 if (Matches.empty())
4453 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004454 else if (Matches.size() == 1) {
4455 FunctionDecl *Result = *Matches.begin();
4456 MarkDeclarationReferenced(From->getLocStart(), Result);
4457 return Result;
4458 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004459
4460 // C++ [over.over]p4:
4461 // If more than one function is selected, [...]
Douglas Gregor05155d82009-08-21 23:19:43 +00004462 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorfae1d712009-09-26 03:56:17 +00004463 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004464 // [...] and any given function template specialization F1 is
4465 // eliminated if the set contains a second function template
4466 // specialization whose function template is more specialized
4467 // than the function template of F1 according to the partial
4468 // ordering rules of 14.5.5.2.
4469
4470 // The algorithm specified above is quadratic. We instead use a
4471 // two-pass algorithm (similar to the one used to identify the
4472 // best viable function in an overload set) that identifies the
4473 // best function template (if it exists).
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004474 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregorfae1d712009-09-26 03:56:17 +00004475 Matches.end());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004476 FunctionDecl *Result =
4477 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4478 TPOC_Other, From->getLocStart(),
4479 PDiag(),
4480 PDiag(diag::err_addr_ovl_ambiguous)
4481 << TemplateMatches[0]->getDeclName(),
4482 PDiag(diag::err_ovl_template_candidate));
4483 MarkDeclarationReferenced(From->getLocStart(), Result);
4484 return Result;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004485 }
Mike Stump11289f42009-09-09 15:08:12 +00004486
Douglas Gregorfae1d712009-09-26 03:56:17 +00004487 // [...] any function template specializations in the set are
4488 // eliminated if the set also contains a non-template function, [...]
4489 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4490 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4491 if ((*M)->getPrimaryTemplate() == 0)
4492 RemainingMatches.push_back(*M);
4493
Mike Stump11289f42009-09-09 15:08:12 +00004494 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004495 // selected function.
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004496 if (RemainingMatches.size() == 1) {
4497 FunctionDecl *Result = RemainingMatches.front();
4498 MarkDeclarationReferenced(From->getLocStart(), Result);
4499 return Result;
4500 }
Mike Stump11289f42009-09-09 15:08:12 +00004501
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004502 // FIXME: We should probably return the same thing that BestViableFunction
4503 // returns (even if we issue the diagnostics here).
4504 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4505 << RemainingMatches[0]->getDeclName();
4506 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4507 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004508 return 0;
4509}
4510
Douglas Gregorcabea402009-09-22 15:41:20 +00004511/// \brief Add a single candidate to the overload set.
4512static void AddOverloadedCallCandidate(Sema &S,
John McCalld14a8642009-11-21 08:51:07 +00004513 NamedDecl *Callee,
John McCall6b51f282009-11-23 01:53:49 +00004514 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004515 Expr **Args, unsigned NumArgs,
4516 OverloadCandidateSet &CandidateSet,
4517 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00004518 if (isa<UsingShadowDecl>(Callee))
4519 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
4520
Douglas Gregorcabea402009-09-22 15:41:20 +00004521 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00004522 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregorcabea402009-09-22 15:41:20 +00004523 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4524 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004525 return;
John McCalld14a8642009-11-21 08:51:07 +00004526 }
4527
4528 if (FunctionTemplateDecl *FuncTemplate
4529 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00004530 S.AddTemplateOverloadCandidate(FuncTemplate, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00004531 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00004532 return;
4533 }
4534
4535 assert(false && "unhandled case in overloaded call candidate");
4536
4537 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00004538}
4539
4540/// \brief Add the overload candidates named by callee and/or found by argument
4541/// dependent lookup to the given overload set.
John McCalld14a8642009-11-21 08:51:07 +00004542void Sema::AddOverloadedCallCandidates(llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregorcabea402009-09-22 15:41:20 +00004543 DeclarationName &UnqualifiedName,
John McCall4b1f16e2009-11-21 09:38:42 +00004544 bool ArgumentDependentLookup,
John McCall6b51f282009-11-23 01:53:49 +00004545 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004546 Expr **Args, unsigned NumArgs,
4547 OverloadCandidateSet &CandidateSet,
4548 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00004549
4550#ifndef NDEBUG
4551 // Verify that ArgumentDependentLookup is consistent with the rules
4552 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00004553 //
Douglas Gregorcabea402009-09-22 15:41:20 +00004554 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4555 // and let Y be the lookup set produced by argument dependent
4556 // lookup (defined as follows). If X contains
4557 //
4558 // -- a declaration of a class member, or
4559 //
4560 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00004561 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00004562 //
4563 // -- a declaration that is neither a function or a function
4564 // template
4565 //
4566 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00004567
4568 if (ArgumentDependentLookup) {
4569 for (unsigned I = 0; I < Fns.size(); ++I) {
4570 assert(!Fns[I]->getDeclContext()->isRecord());
4571 assert(isa<UsingShadowDecl>(Fns[I]) ||
4572 !Fns[I]->getDeclContext()->isFunctionOrMethod());
4573 assert(Fns[I]->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
4574 }
4575 }
4576#endif
4577
4578 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4579 E = Fns.end(); I != E; ++I)
John McCall6b51f282009-11-23 01:53:49 +00004580 AddOverloadedCallCandidate(*this, *I, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00004581 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00004582 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00004583
Douglas Gregorcabea402009-09-22 15:41:20 +00004584 if (ArgumentDependentLookup)
4585 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004586 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004587 CandidateSet,
4588 PartialOverloading);
4589}
4590
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004591/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00004592/// (which eventually refers to the declaration Func) and the call
4593/// arguments Args/NumArgs, attempt to resolve the function call down
4594/// to a specific function. If overload resolution succeeds, returns
4595/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00004596/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004597/// arguments and Fn, and returns NULL.
John McCalld14a8642009-11-21 08:51:07 +00004598FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn,
4599 llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004600 DeclarationName UnqualifiedName,
John McCall6b51f282009-11-23 01:53:49 +00004601 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregora60a6912008-11-26 06:01:48 +00004602 SourceLocation LParenLoc,
4603 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004604 SourceLocation *CommaLocs,
Douglas Gregore254f902009-02-04 00:32:51 +00004605 SourceLocation RParenLoc,
John McCall4b1f16e2009-11-21 09:38:42 +00004606 bool ArgumentDependentLookup) {
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004607 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004608
4609 // Add the functions denoted by Callee to the set of candidate
Douglas Gregorcabea402009-09-22 15:41:20 +00004610 // functions.
John McCalld14a8642009-11-21 08:51:07 +00004611 AddOverloadedCallCandidates(Fns, UnqualifiedName, ArgumentDependentLookup,
John McCall6b51f282009-11-23 01:53:49 +00004612 ExplicitTemplateArgs, Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004613 CandidateSet);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004614 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004615 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregora60a6912008-11-26 06:01:48 +00004616 case OR_Success:
4617 return Best->Function;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004618
4619 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00004620 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004621 diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004622 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004623 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4624 break;
4625
4626 case OR_Ambiguous:
4627 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004628 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004629 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4630 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004631
4632 case OR_Deleted:
4633 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4634 << Best->Function->isDeleted()
4635 << UnqualifiedName
4636 << Fn->getSourceRange();
4637 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4638 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004639 }
4640
4641 // Overload resolution failed. Destroy all of the subexpressions and
4642 // return NULL.
4643 Fn->Destroy(Context);
4644 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4645 Args[Arg]->Destroy(Context);
4646 return 0;
4647}
4648
John McCall283b9012009-11-22 00:44:51 +00004649static bool IsOverloaded(const Sema::FunctionSet &Functions) {
4650 return Functions.size() > 1 ||
4651 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
4652}
4653
Douglas Gregor084d8552009-03-13 23:49:33 +00004654/// \brief Create a unary operation that may resolve to an overloaded
4655/// operator.
4656///
4657/// \param OpLoc The location of the operator itself (e.g., '*').
4658///
4659/// \param OpcIn The UnaryOperator::Opcode that describes this
4660/// operator.
4661///
4662/// \param Functions The set of non-member functions that will be
4663/// considered by overload resolution. The caller needs to build this
4664/// set based on the context using, e.g.,
4665/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4666/// set should not contain any member functions; those will be added
4667/// by CreateOverloadedUnaryOp().
4668///
4669/// \param input The input argument.
4670Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4671 unsigned OpcIn,
4672 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00004673 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004674 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4675 Expr *Input = (Expr *)input.get();
4676
4677 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4678 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4679 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4680
4681 Expr *Args[2] = { Input, 0 };
4682 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004683
Douglas Gregor084d8552009-03-13 23:49:33 +00004684 // For post-increment and post-decrement, add the implicit '0' as
4685 // the second argument, so that we know this is a post-increment or
4686 // post-decrement.
4687 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4688 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00004689 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00004690 SourceLocation());
4691 NumArgs = 2;
4692 }
4693
4694 if (Input->isTypeDependent()) {
John McCalld14a8642009-11-21 08:51:07 +00004695 UnresolvedLookupExpr *Fn
4696 = UnresolvedLookupExpr::Create(Context, 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00004697 /*ADL*/ true, IsOverloaded(Functions));
Mike Stump11289f42009-09-09 15:08:12 +00004698 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00004699 FuncEnd = Functions.end();
4700 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00004701 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00004702
Douglas Gregor084d8552009-03-13 23:49:33 +00004703 input.release();
4704 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4705 &Args[0], NumArgs,
4706 Context.DependentTy,
4707 OpLoc));
4708 }
4709
4710 // Build an empty overload set.
4711 OverloadCandidateSet CandidateSet;
4712
4713 // Add the candidates from the given function set.
4714 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4715
4716 // Add operator candidates that are member functions.
4717 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4718
4719 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004720 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00004721
4722 // Perform overload resolution.
4723 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004724 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004725 case OR_Success: {
4726 // We found a built-in operator or an overloaded operator.
4727 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00004728
Douglas Gregor084d8552009-03-13 23:49:33 +00004729 if (FnDecl) {
4730 // We matched an overloaded operator. Build a call to that
4731 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00004732
Douglas Gregor084d8552009-03-13 23:49:33 +00004733 // Convert the arguments.
4734 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4735 if (PerformObjectArgumentInitialization(Input, Method))
4736 return ExprError();
4737 } else {
4738 // Convert the arguments.
4739 if (PerformCopyInitialization(Input,
4740 FnDecl->getParamDecl(0)->getType(),
4741 "passing"))
4742 return ExprError();
4743 }
4744
4745 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004746 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004747
Douglas Gregor084d8552009-03-13 23:49:33 +00004748 // Build the actual expression node.
4749 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4750 SourceLocation());
4751 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004752
Douglas Gregor084d8552009-03-13 23:49:33 +00004753 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00004754 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004755 ExprOwningPtr<CallExpr> TheCall(this,
4756 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00004757 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004758
4759 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4760 FnDecl))
4761 return ExprError();
4762
4763 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00004764 } else {
4765 // We matched a built-in operator. Convert the arguments, then
4766 // break out so that we will build the appropriate built-in
4767 // operator node.
4768 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4769 Best->Conversions[0], "passing"))
4770 return ExprError();
4771
4772 break;
4773 }
4774 }
4775
4776 case OR_No_Viable_Function:
4777 // No viable function; fall through to handling this as a
4778 // built-in operator, which will produce an error message for us.
4779 break;
4780
4781 case OR_Ambiguous:
4782 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4783 << UnaryOperator::getOpcodeStr(Opc)
4784 << Input->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004785 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4786 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00004787 return ExprError();
4788
4789 case OR_Deleted:
4790 Diag(OpLoc, diag::err_ovl_deleted_oper)
4791 << Best->Function->isDeleted()
4792 << UnaryOperator::getOpcodeStr(Opc)
4793 << Input->getSourceRange();
4794 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4795 return ExprError();
4796 }
4797
4798 // Either we found no viable overloaded operator or we matched a
4799 // built-in operator. In either case, fall through to trying to
4800 // build a built-in operation.
4801 input.release();
4802 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4803}
4804
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004805/// \brief Create a binary operation that may resolve to an overloaded
4806/// operator.
4807///
4808/// \param OpLoc The location of the operator itself (e.g., '+').
4809///
4810/// \param OpcIn The BinaryOperator::Opcode that describes this
4811/// operator.
4812///
4813/// \param Functions The set of non-member functions that will be
4814/// considered by overload resolution. The caller needs to build this
4815/// set based on the context using, e.g.,
4816/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4817/// set should not contain any member functions; those will be added
4818/// by CreateOverloadedBinOp().
4819///
4820/// \param LHS Left-hand argument.
4821/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00004822Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004823Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004824 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004825 FunctionSet &Functions,
4826 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004827 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00004828 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004829
4830 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4831 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4832 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4833
4834 // If either side is type-dependent, create an appropriate dependent
4835 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00004836 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00004837 if (Functions.empty()) {
4838 // If there are no functions to store, just build a dependent
4839 // BinaryOperator or CompoundAssignment.
4840 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
4841 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
4842 Context.DependentTy, OpLoc));
4843
4844 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
4845 Context.DependentTy,
4846 Context.DependentTy,
4847 Context.DependentTy,
4848 OpLoc));
4849 }
4850
John McCalld14a8642009-11-21 08:51:07 +00004851 UnresolvedLookupExpr *Fn
4852 = UnresolvedLookupExpr::Create(Context, 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00004853 /* ADL */ true, IsOverloaded(Functions));
John McCalld14a8642009-11-21 08:51:07 +00004854
Mike Stump11289f42009-09-09 15:08:12 +00004855 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004856 FuncEnd = Functions.end();
4857 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00004858 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00004859
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004860 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00004861 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004862 Context.DependentTy,
4863 OpLoc));
4864 }
4865
4866 // If this is the .* operator, which is not overloadable, just
4867 // create a built-in binary operator.
4868 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004869 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004870
Sebastian Redl6a96bf72009-11-18 23:10:33 +00004871 // If this is the assignment operator, we only perform overload resolution
4872 // if the left-hand side is a class or enumeration type. This is actually
4873 // a hack. The standard requires that we do overload resolution between the
4874 // various built-in candidates, but as DR507 points out, this can lead to
4875 // problems. So we do it this way, which pretty much follows what GCC does.
4876 // Note that we go the traditional code path for compound assignment forms.
4877 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00004878 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004879
Douglas Gregor084d8552009-03-13 23:49:33 +00004880 // Build an empty overload set.
4881 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004882
4883 // Add the candidates from the given function set.
4884 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4885
4886 // Add operator candidates that are member functions.
4887 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4888
4889 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004890 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004891
4892 // Perform overload resolution.
4893 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004894 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004895 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004896 // We found a built-in operator or an overloaded operator.
4897 FunctionDecl *FnDecl = Best->Function;
4898
4899 if (FnDecl) {
4900 // We matched an overloaded operator. Build a call to that
4901 // operator.
4902
4903 // Convert the arguments.
4904 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregore9899d92009-08-26 17:08:25 +00004905 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4906 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004907 "passing"))
4908 return ExprError();
4909 } else {
4910 // Convert the arguments.
Douglas Gregore9899d92009-08-26 17:08:25 +00004911 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004912 "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004913 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004914 "passing"))
4915 return ExprError();
4916 }
4917
4918 // Determine the result type
4919 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00004920 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004921 ResultTy = ResultTy.getNonReferenceType();
4922
4923 // Build the actual expression node.
4924 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00004925 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004926 UsualUnaryConversions(FnExpr);
4927
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00004928 ExprOwningPtr<CXXOperatorCallExpr>
4929 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4930 Args, 2, ResultTy,
4931 OpLoc));
4932
4933 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4934 FnDecl))
4935 return ExprError();
4936
4937 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004938 } else {
4939 // We matched a built-in operator. Convert the arguments, then
4940 // break out so that we will build the appropriate built-in
4941 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00004942 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004943 Best->Conversions[0], "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004944 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004945 Best->Conversions[1], "passing"))
4946 return ExprError();
4947
4948 break;
4949 }
4950 }
4951
Douglas Gregor66950a32009-09-30 21:46:01 +00004952 case OR_No_Viable_Function: {
4953 // C++ [over.match.oper]p9:
4954 // If the operator is the operator , [...] and there are no
4955 // viable functions, then the operator is assumed to be the
4956 // built-in operator and interpreted according to clause 5.
4957 if (Opc == BinaryOperator::Comma)
4958 break;
4959
Sebastian Redl027de2a2009-05-21 11:50:50 +00004960 // For class as left operand for assignment or compound assigment operator
4961 // do not fall through to handling in built-in, but report that no overloaded
4962 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00004963 OwningExprResult Result = ExprError();
4964 if (Args[0]->getType()->isRecordType() &&
4965 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00004966 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4967 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004968 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00004969 } else {
4970 // No viable function; try to create a built-in operation, which will
4971 // produce an error. Then, show the non-viable candidates.
4972 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00004973 }
Douglas Gregor66950a32009-09-30 21:46:01 +00004974 assert(Result.isInvalid() &&
4975 "C++ binary operator overloading is missing candidates!");
4976 if (Result.isInvalid())
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004977 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
4978 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00004979 return move(Result);
4980 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004981
4982 case OR_Ambiguous:
4983 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4984 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004985 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004986 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4987 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004988 return ExprError();
4989
4990 case OR_Deleted:
4991 Diag(OpLoc, diag::err_ovl_deleted_oper)
4992 << Best->Function->isDeleted()
4993 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004994 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004995 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4996 return ExprError();
4997 }
4998
Douglas Gregor66950a32009-09-30 21:46:01 +00004999 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00005000 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005001}
5002
Sebastian Redladba46e2009-10-29 20:17:01 +00005003Action::OwningExprResult
5004Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5005 SourceLocation RLoc,
5006 ExprArg Base, ExprArg Idx) {
5007 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5008 static_cast<Expr*>(Idx.get()) };
5009 DeclarationName OpName =
5010 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5011
5012 // If either side is type-dependent, create an appropriate dependent
5013 // expression.
5014 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5015
John McCalld14a8642009-11-21 08:51:07 +00005016 UnresolvedLookupExpr *Fn
5017 = UnresolvedLookupExpr::Create(Context, 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00005018 /*ADL*/ true, /*Overloaded*/ false);
John McCalld14a8642009-11-21 08:51:07 +00005019 // Can't add an actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00005020
5021 Base.release();
5022 Idx.release();
5023 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5024 Args, 2,
5025 Context.DependentTy,
5026 RLoc));
5027 }
5028
5029 // Build an empty overload set.
5030 OverloadCandidateSet CandidateSet;
5031
5032 // Subscript can only be overloaded as a member function.
5033
5034 // Add operator candidates that are member functions.
5035 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5036
5037 // Add builtin operator candidates.
5038 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5039
5040 // Perform overload resolution.
5041 OverloadCandidateSet::iterator Best;
5042 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5043 case OR_Success: {
5044 // We found a built-in operator or an overloaded operator.
5045 FunctionDecl *FnDecl = Best->Function;
5046
5047 if (FnDecl) {
5048 // We matched an overloaded operator. Build a call to that
5049 // operator.
5050
5051 // Convert the arguments.
5052 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5053 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5054 PerformCopyInitialization(Args[1],
5055 FnDecl->getParamDecl(0)->getType(),
5056 "passing"))
5057 return ExprError();
5058
5059 // Determine the result type
5060 QualType ResultTy
5061 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5062 ResultTy = ResultTy.getNonReferenceType();
5063
5064 // Build the actual expression node.
5065 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5066 LLoc);
5067 UsualUnaryConversions(FnExpr);
5068
5069 Base.release();
5070 Idx.release();
5071 ExprOwningPtr<CXXOperatorCallExpr>
5072 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5073 FnExpr, Args, 2,
5074 ResultTy, RLoc));
5075
5076 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5077 FnDecl))
5078 return ExprError();
5079
5080 return MaybeBindToTemporary(TheCall.release());
5081 } else {
5082 // We matched a built-in operator. Convert the arguments, then
5083 // break out so that we will build the appropriate built-in
5084 // operator node.
5085 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
5086 Best->Conversions[0], "passing") ||
5087 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
5088 Best->Conversions[1], "passing"))
5089 return ExprError();
5090
5091 break;
5092 }
5093 }
5094
5095 case OR_No_Viable_Function: {
5096 // No viable function; try to create a built-in operation, which will
5097 // produce an error. Then, show the non-viable candidates.
5098 OwningExprResult Result =
5099 CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
5100 assert(Result.isInvalid() &&
5101 "C++ subscript operator overloading is missing candidates!");
5102 if (Result.isInvalid())
5103 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5104 "[]", LLoc);
5105 return move(Result);
5106 }
5107
5108 case OR_Ambiguous:
5109 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5110 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5111 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5112 "[]", LLoc);
5113 return ExprError();
5114
5115 case OR_Deleted:
5116 Diag(LLoc, diag::err_ovl_deleted_oper)
5117 << Best->Function->isDeleted() << "[]"
5118 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5119 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5120 return ExprError();
5121 }
5122
5123 // We matched a built-in operator; build it.
5124 Base.release();
5125 Idx.release();
5126 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5127 Owned(Args[1]), RLoc);
5128}
5129
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005130/// BuildCallToMemberFunction - Build a call to a member
5131/// function. MemExpr is the expression that refers to the member
5132/// function (and includes the object parameter), Args/NumArgs are the
5133/// arguments to the function call (not including the object
5134/// parameter). The caller needs to validate that the member
5135/// expression refers to a member function or an overloaded member
5136/// function.
5137Sema::ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00005138Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5139 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005140 unsigned NumArgs, SourceLocation *CommaLocs,
5141 SourceLocation RParenLoc) {
5142 // Dig out the member expression. This holds both the object
5143 // argument and the member function we're referring to.
5144 MemberExpr *MemExpr = 0;
5145 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
5146 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
5147 else
5148 MemExpr = dyn_cast<MemberExpr>(MemExprE);
5149 assert(MemExpr && "Building member call without member expression");
5150
5151 // Extract the object argument.
5152 Expr *ObjectArg = MemExpr->getBase();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005153
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005154 CXXMethodDecl *Method = 0;
Douglas Gregor97628d62009-08-21 00:16:32 +00005155 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
5156 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005157 // Add overload candidates
5158 OverloadCandidateSet CandidateSet;
Douglas Gregor97628d62009-08-21 00:16:32 +00005159 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00005160
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005161 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
5162 Func != FuncEnd; ++Func) {
Douglas Gregord3319842009-10-24 04:59:53 +00005163 if ((Method = dyn_cast<CXXMethodDecl>(*Func))) {
5164 // If explicit template arguments were provided, we can't call a
5165 // non-template member function.
5166 if (MemExpr->hasExplicitTemplateArgumentList())
5167 continue;
5168
Mike Stump11289f42009-09-09 15:08:12 +00005169 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005170 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005171 } else {
5172 // FIXME: avoid copy.
5173 TemplateArgumentListInfo TemplateArgs;
5174 if (MemExpr->hasExplicitTemplateArgumentList())
5175 MemExpr->copyTemplateArgumentsInto(TemplateArgs);
5176
Douglas Gregor84f14dd2009-09-01 00:37:14 +00005177 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
John McCall6b51f282009-11-23 01:53:49 +00005178 (MemExpr->hasExplicitTemplateArgumentList()
5179 ? &TemplateArgs : 0),
Douglas Gregor84f14dd2009-09-01 00:37:14 +00005180 ObjectArg, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005181 CandidateSet,
5182 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005183 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005184 }
Mike Stump11289f42009-09-09 15:08:12 +00005185
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005186 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005187 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005188 case OR_Success:
5189 Method = cast<CXXMethodDecl>(Best->Function);
5190 break;
5191
5192 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00005193 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005194 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005195 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005196 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5197 // FIXME: Leaking incoming expressions!
5198 return true;
5199
5200 case OR_Ambiguous:
Mike Stump11289f42009-09-09 15:08:12 +00005201 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005202 diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005203 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005204 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5205 // FIXME: Leaking incoming expressions!
5206 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005207
5208 case OR_Deleted:
Mike Stump11289f42009-09-09 15:08:12 +00005209 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00005210 diag::err_ovl_deleted_member_call)
5211 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00005212 << DeclName << MemExprE->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005213 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5214 // FIXME: Leaking incoming expressions!
5215 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005216 }
5217
Douglas Gregor51c538b2009-11-20 19:42:02 +00005218 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
5219 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
5220 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
5221 else
5222 MemExpr = dyn_cast<MemberExpr>(MemExprE);
5223
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005224 } else {
5225 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5226 }
5227
5228 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00005229 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005230 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
Mike Stump11289f42009-09-09 15:08:12 +00005231 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005232 Method->getResultType().getNonReferenceType(),
5233 RParenLoc));
5234
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005235 // Check for a valid return type.
5236 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5237 TheCall.get(), Method))
5238 return true;
5239
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005240 // Convert the object argument (for a non-static member function call).
Mike Stump11289f42009-09-09 15:08:12 +00005241 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005242 PerformObjectArgumentInitialization(ObjectArg, Method))
5243 return true;
5244 MemExpr->setBase(ObjectArg);
5245
5246 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005247 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00005248 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005249 RParenLoc))
5250 return true;
5251
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005252 if (CheckFunctionCall(Method, TheCall.get()))
5253 return true;
Anders Carlsson8c84c202009-08-16 03:42:12 +00005254
5255 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005256}
5257
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005258/// BuildCallToObjectOfClassType - Build a call to an object of class
5259/// type (C++ [over.call.object]), which can end up invoking an
5260/// overloaded function call operator (@c operator()) or performing a
5261/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00005262Sema::ExprResult
5263Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00005264 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005265 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00005266 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005267 SourceLocation RParenLoc) {
5268 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005269 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00005270
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005271 // C++ [over.call.object]p1:
5272 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00005273 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005274 // candidate functions includes at least the function call
5275 // operators of T. The function call operators of T are obtained by
5276 // ordinary lookup of the name operator() in the context of
5277 // (E).operator().
5278 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00005279 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005280
5281 if (RequireCompleteType(LParenLoc, Object->getType(),
5282 PartialDiagnostic(diag::err_incomplete_object_call)
5283 << Object->getSourceRange()))
5284 return true;
5285
John McCall27b18f82009-11-17 02:14:36 +00005286 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5287 LookupQualifiedName(R, Record->getDecl());
5288 R.suppressDiagnostics();
5289
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005290 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00005291 Oper != OperEnd; ++Oper) {
John McCallf0f1cf02009-11-17 07:50:12 +00005292 AddMethodCandidate(*Oper, Object, Args, NumArgs, CandidateSet,
5293 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00005294 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005295
Douglas Gregorab7897a2008-11-19 22:57:39 +00005296 // C++ [over.call.object]p2:
5297 // In addition, for each conversion function declared in T of the
5298 // form
5299 //
5300 // operator conversion-type-id () cv-qualifier;
5301 //
5302 // where cv-qualifier is the same cv-qualification as, or a
5303 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00005304 // denotes the type "pointer to function of (P1,...,Pn) returning
5305 // R", or the type "reference to pointer to function of
5306 // (P1,...,Pn) returning R", or the type "reference to function
5307 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00005308 // is also considered as a candidate function. Similarly,
5309 // surrogate call functions are added to the set of candidate
5310 // functions for each conversion function declared in an
5311 // accessible base class provided the function is not hidden
5312 // within T by another intervening declaration.
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005313 // FIXME: Look in base classes for more conversion operators!
John McCalld14a8642009-11-21 08:51:07 +00005314 const UnresolvedSet *Conversions
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005315 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00005316 for (UnresolvedSet::iterator I = Conversions->begin(),
5317 E = Conversions->end(); I != E; ++I) {
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005318 // Skip over templated conversion functions; they aren't
5319 // surrogates.
John McCalld14a8642009-11-21 08:51:07 +00005320 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005321 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005322
John McCalld14a8642009-11-21 08:51:07 +00005323 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
5324
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005325 // Strip the reference type (if any) and then the pointer type (if
5326 // any) to get down to what might be a function type.
5327 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5328 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5329 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005330
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005331 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
5332 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00005333 }
Mike Stump11289f42009-09-09 15:08:12 +00005334
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005335 // Perform overload resolution.
5336 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005337 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005338 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00005339 // Overload resolution succeeded; we'll build the appropriate call
5340 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005341 break;
5342
5343 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00005344 Diag(Object->getSourceRange().getBegin(),
Sebastian Redl15b02d22008-11-22 13:44:36 +00005345 diag::err_ovl_no_viable_object_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00005346 << Object->getType() << Object->getSourceRange();
Sebastian Redl15b02d22008-11-22 13:44:36 +00005347 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005348 break;
5349
5350 case OR_Ambiguous:
5351 Diag(Object->getSourceRange().getBegin(),
5352 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005353 << Object->getType() << Object->getSourceRange();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005354 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5355 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005356
5357 case OR_Deleted:
5358 Diag(Object->getSourceRange().getBegin(),
5359 diag::err_ovl_deleted_object_call)
5360 << Best->Function->isDeleted()
5361 << Object->getType() << Object->getSourceRange();
5362 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5363 break;
Mike Stump11289f42009-09-09 15:08:12 +00005364 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005365
Douglas Gregorab7897a2008-11-19 22:57:39 +00005366 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005367 // We had an error; delete all of the subexpressions and return
5368 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00005369 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005370 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00005371 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005372 return true;
5373 }
5374
Douglas Gregorab7897a2008-11-19 22:57:39 +00005375 if (Best->Function == 0) {
5376 // Since there is no function declaration, this is one of the
5377 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00005378 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00005379 = cast<CXXConversionDecl>(
5380 Best->Conversions[0].UserDefined.ConversionFunction);
5381
5382 // We selected one of the surrogate functions that converts the
5383 // object parameter to a function pointer. Perform the conversion
5384 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005385
5386 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005387 // and then call it.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005388 CXXMemberCallExpr *CE =
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005389 BuildCXXMemberCallExpr(Object, Conv);
5390
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005391 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005392 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5393 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005394 }
5395
5396 // We found an overloaded operator(). Build a CXXOperatorCallExpr
5397 // that calls this method, using Object for the implicit object
5398 // parameter and passing along the remaining arguments.
5399 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00005400 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005401
5402 unsigned NumArgsInProto = Proto->getNumArgs();
5403 unsigned NumArgsToCheck = NumArgs;
5404
5405 // Build the full argument list for the method call (the
5406 // implicit object parameter is placed at the beginning of the
5407 // list).
5408 Expr **MethodArgs;
5409 if (NumArgs < NumArgsInProto) {
5410 NumArgsToCheck = NumArgsInProto;
5411 MethodArgs = new Expr*[NumArgsInProto + 1];
5412 } else {
5413 MethodArgs = new Expr*[NumArgs + 1];
5414 }
5415 MethodArgs[0] = Object;
5416 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5417 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00005418
5419 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00005420 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005421 UsualUnaryConversions(NewFn);
5422
5423 // Once we've built TheCall, all of the expressions are properly
5424 // owned.
5425 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005426 ExprOwningPtr<CXXOperatorCallExpr>
5427 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005428 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00005429 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005430 delete [] MethodArgs;
5431
Anders Carlsson3d5829c2009-10-13 21:49:31 +00005432 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5433 Method))
5434 return true;
5435
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005436 // We may have default arguments. If so, we need to allocate more
5437 // slots in the call for them.
5438 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00005439 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005440 else if (NumArgs > NumArgsInProto)
5441 NumArgsToCheck = NumArgsInProto;
5442
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005443 bool IsError = false;
5444
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005445 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005446 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005447 TheCall->setArg(0, Object);
5448
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005449
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005450 // Check the argument types.
5451 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005452 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005453 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005454 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00005455
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005456 // Pass the argument.
5457 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005458 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005459 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00005460 OwningExprResult DefArg
5461 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
5462 if (DefArg.isInvalid()) {
5463 IsError = true;
5464 break;
5465 }
5466
5467 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005468 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005469
5470 TheCall->setArg(i + 1, Arg);
5471 }
5472
5473 // If this is a variadic call, handle args passed through "...".
5474 if (Proto->isVariadic()) {
5475 // Promote the arguments (C99 6.5.2.2p7).
5476 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5477 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005478 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005479 TheCall->setArg(i + 1, Arg);
5480 }
5481 }
5482
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005483 if (IsError) return true;
5484
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005485 if (CheckFunctionCall(Method, TheCall.get()))
5486 return true;
5487
Anders Carlsson1c83deb2009-08-16 03:53:54 +00005488 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005489}
5490
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005491/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00005492/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005493/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00005494Sema::OwningExprResult
5495Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5496 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005497 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00005498
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005499 // C++ [over.ref]p1:
5500 //
5501 // [...] An expression x->m is interpreted as (x.operator->())->m
5502 // for a class object x of type T if T::operator->() exists and if
5503 // the operator is selected as the best match function by the
5504 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005505 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5506 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005507 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00005508
Eli Friedman132e70b2009-11-18 01:28:03 +00005509 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
5510 PDiag(diag::err_typecheck_incomplete_tag)
5511 << Base->getSourceRange()))
5512 return ExprError();
5513
John McCall27b18f82009-11-17 02:14:36 +00005514 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
5515 LookupQualifiedName(R, BaseRecord->getDecl());
5516 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00005517
5518 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
5519 Oper != OperEnd; ++Oper)
Douglas Gregor55297ac2008-12-23 00:26:44 +00005520 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005521 /*SuppressUserConversions=*/false);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005522
5523 // Perform overload resolution.
5524 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005525 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005526 case OR_Success:
5527 // Overload resolution succeeded; we'll build the call below.
5528 break;
5529
5530 case OR_No_Viable_Function:
5531 if (CandidateSet.empty())
5532 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00005533 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005534 else
5535 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00005536 << "operator->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005537 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregord8061562009-08-06 03:17:00 +00005538 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005539
5540 case OR_Ambiguous:
5541 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00005542 << "->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005543 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005544 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005545
5546 case OR_Deleted:
5547 Diag(OpLoc, diag::err_ovl_deleted_oper)
5548 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00005549 << "->" << Base->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005550 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005551 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005552 }
5553
5554 // Convert the object parameter.
5555 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00005556 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00005557 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00005558
5559 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00005560 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005561
5562 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00005563 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5564 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005565 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005566
5567 QualType ResultTy = Method->getResultType().getNonReferenceType();
5568 ExprOwningPtr<CXXOperatorCallExpr>
5569 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
5570 &Base, 1, ResultTy, OpLoc));
5571
5572 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
5573 Method))
5574 return ExprError();
5575 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005576}
5577
Douglas Gregorcd695e52008-11-10 20:40:00 +00005578/// FixOverloadedFunctionReference - E is an expression that refers to
5579/// a C++ overloaded function (possibly with some parentheses and
5580/// perhaps a '&' around it). We have resolved the overloaded function
5581/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005582/// refer (possibly indirectly) to Fn. Returns the new expr.
5583Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005584 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor51c538b2009-11-20 19:42:02 +00005585 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5586 if (SubExpr == PE->getSubExpr())
5587 return PE->Retain();
5588
5589 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
5590 }
5591
5592 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5593 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00005594 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00005595 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00005596 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00005597 if (SubExpr == ICE->getSubExpr())
5598 return ICE->Retain();
5599
5600 return new (Context) ImplicitCastExpr(ICE->getType(),
5601 ICE->getCastKind(),
5602 SubExpr,
5603 ICE->isLvalueCast());
5604 }
5605
5606 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00005607 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00005608 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005609 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5610 if (Method->isStatic()) {
5611 // Do nothing: static member functions aren't any different
5612 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00005613 } else {
5614 // Fix the sub expression, which really has to be one of:
5615 // * a DeclRefExpr holding a member function template
5616 // * a TemplateIdRefExpr, also holding a member function template
5617 // * an UnresolvedLookupExpr holding an overloaded member function
5618 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5619 if (SubExpr == UnOp->getSubExpr())
5620 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00005621
John McCalld14a8642009-11-21 08:51:07 +00005622 assert(isa<DeclRefExpr>(SubExpr)
5623 && "fixed to something other than a decl ref");
5624 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
5625 && "fixed to a member ref with no nested name qualifier");
5626
5627 // We have taken the address of a pointer to member
5628 // function. Perform the computation here so that we get the
5629 // appropriate pointer to member type.
5630 QualType ClassType
5631 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5632 QualType MemPtrType
5633 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
5634
5635 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5636 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005637 }
John McCalld14a8642009-11-21 08:51:07 +00005638
Douglas Gregor6a573fe2009-10-22 18:02:20 +00005639 // FIXME: TemplateIdRefExpr referring to a member function template
5640 // specialization!
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005641 }
Douglas Gregor51c538b2009-11-20 19:42:02 +00005642 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5643 if (SubExpr == UnOp->getSubExpr())
5644 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005645
Douglas Gregor51c538b2009-11-20 19:42:02 +00005646 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5647 Context.getPointerType(SubExpr->getType()),
5648 UnOp->getOperatorLoc());
5649 }
5650
5651 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
John McCalld14a8642009-11-21 08:51:07 +00005652 assert((isa<FunctionTemplateDecl>(DRE->getDecl()) ||
Douglas Gregor51c538b2009-11-20 19:42:02 +00005653 isa<FunctionDecl>(DRE->getDecl())) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00005654 "Expected function or function template");
John McCall6b51f282009-11-23 01:53:49 +00005655 // FIXME: avoid copy.
5656 TemplateArgumentListInfo TemplateArgs;
5657 if (DRE->hasExplicitTemplateArgumentList())
5658 DRE->copyTemplateArgumentsInto(TemplateArgs);
5659
Douglas Gregor51c538b2009-11-20 19:42:02 +00005660 return DeclRefExpr::Create(Context,
5661 DRE->getQualifier(),
5662 DRE->getQualifierRange(),
5663 Fn,
5664 DRE->getLocation(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00005665 Fn->getType(),
Douglas Gregored6c7442009-11-23 11:41:28 +00005666 (DRE->hasExplicitTemplateArgumentList()
5667 ? &TemplateArgs : 0));
Douglas Gregor51c538b2009-11-20 19:42:02 +00005668 }
John McCalld14a8642009-11-21 08:51:07 +00005669
5670 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
5671 return DeclRefExpr::Create(Context,
5672 ULE->getQualifier(),
5673 ULE->getQualifierRange(),
5674 Fn,
5675 ULE->getNameLoc(),
Douglas Gregored6c7442009-11-23 11:41:28 +00005676 Fn->getType());
John McCalld14a8642009-11-21 08:51:07 +00005677 }
5678
Douglas Gregor51c538b2009-11-20 19:42:02 +00005679
5680 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
5681 assert((isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
5682 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl()) ||
5683 isa<FunctionDecl>(MemExpr->getMemberDecl())) &&
5684 "Expected member function or member function template");
John McCall6b51f282009-11-23 01:53:49 +00005685 // FIXME: avoid copy.
5686 TemplateArgumentListInfo TemplateArgs;
5687 if (MemExpr->hasExplicitTemplateArgumentList())
5688 MemExpr->copyTemplateArgumentsInto(TemplateArgs);
5689
Douglas Gregor51c538b2009-11-20 19:42:02 +00005690 return MemberExpr::Create(Context, MemExpr->getBase()->Retain(),
5691 MemExpr->isArrow(),
5692 MemExpr->getQualifier(),
5693 MemExpr->getQualifierRange(),
5694 Fn,
John McCall6b51f282009-11-23 01:53:49 +00005695 MemExpr->getMemberLoc(),
5696 (MemExpr->hasExplicitTemplateArgumentList()
5697 ? &TemplateArgs : 0),
Douglas Gregor51c538b2009-11-20 19:42:02 +00005698 Fn->getType());
5699 }
5700
5701 if (TemplateIdRefExpr *TID = dyn_cast<TemplateIdRefExpr>(E)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005702 // FIXME: Don't destroy TID here, since we need its template arguments
5703 // to survive.
5704 // TID->Destroy(Context);
John McCall6b51f282009-11-23 01:53:49 +00005705
5706 // FIXME: avoid copy.
5707 TemplateArgumentListInfo TemplateArgs;
5708 TID->copyTemplateArgumentsInto(TemplateArgs);
5709
Douglas Gregor51c538b2009-11-20 19:42:02 +00005710 return DeclRefExpr::Create(Context,
5711 TID->getQualifier(), TID->getQualifierRange(),
5712 Fn, TID->getTemplateNameLoc(),
Douglas Gregored6c7442009-11-23 11:41:28 +00005713 Fn->getType(),
5714 &TemplateArgs);
Douglas Gregor51c538b2009-11-20 19:42:02 +00005715 }
5716
Douglas Gregor51c538b2009-11-20 19:42:02 +00005717 assert(false && "Invalid reference to overloaded function");
5718 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00005719}
5720
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005721} // end namespace clang