blob: 8d3313982c8e10aff1d1b149cf9d904918f87853 [file] [log] [blame]
Douglas Gregor8e9bebd2008-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 McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor4c2458a2009-12-22 21:44:34 +000016#include "SemaInit.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000027#include <algorithm>
28
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor8e9bebd2008-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,
Douglas Gregor43c79c22009-12-09 00:47:37 +000070 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000071 ICR_Promotion,
72 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000073 ICR_Promotion,
74 ICR_Conversion,
75 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000076 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000081 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000082 ICR_Conversion,
Chandler Carruth23a370f2010-02-25 07:20:54 +000083 ICR_Complex_Real_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000084 };
85 return Rank[(int)Kind];
86}
87
88/// GetImplicitConversionName - Return the name of this kind of
89/// implicit conversion.
90const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +000091 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000092 "No conversion",
93 "Lvalue-to-rvalue",
94 "Array-to-pointer",
95 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +000096 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000097 "Qualification",
98 "Integral promotion",
99 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000100 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000101 "Integral conversion",
102 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000103 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000104 "Floating-integral conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000105 "Complex-real conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000106 "Pointer conversion",
107 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000108 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000109 "Compatible-types conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000110 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000111 };
112 return Name[Kind];
113}
114
Douglas Gregor60d62c22008-10-31 16:23:19 +0000115/// StandardConversionSequence - Set the standard conversion
116/// sequence to the identity conversion.
117void StandardConversionSequence::setAsIdentityConversion() {
118 First = ICK_Identity;
119 Second = ICK_Identity;
120 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000121 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000122 ReferenceBinding = false;
123 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000124 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000125 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000126}
127
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000128/// getRank - Retrieve the rank of this standard conversion sequence
129/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
130/// implicit conversions.
131ImplicitConversionRank StandardConversionSequence::getRank() const {
132 ImplicitConversionRank Rank = ICR_Exact_Match;
133 if (GetConversionRank(First) > Rank)
134 Rank = GetConversionRank(First);
135 if (GetConversionRank(Second) > Rank)
136 Rank = GetConversionRank(Second);
137 if (GetConversionRank(Third) > Rank)
138 Rank = GetConversionRank(Third);
139 return Rank;
140}
141
142/// isPointerConversionToBool - Determines whether this conversion is
143/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000144/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000145/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000146bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000147 // Note that FromType has not necessarily been transformed by the
148 // array-to-pointer or function-to-pointer implicit conversions, so
149 // check for their presence as well as checking whether FromType is
150 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000151 if (getToType(1)->isBooleanType() &&
John McCall1d318332010-01-12 00:44:57 +0000152 (getFromType()->isPointerType() || getFromType()->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000153 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154 return true;
155
156 return false;
157}
158
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000159/// isPointerConversionToVoidPointer - Determines whether this
160/// conversion is a conversion of a pointer to a void pointer. This is
161/// used as part of the ranking of standard conversion sequences (C++
162/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000163bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000166 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000167 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000168
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
174
Douglas Gregor01919692009-12-13 21:37:05 +0000175 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000185 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000186 bool PrintedSomething = false;
187 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000188 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000189 PrintedSomething = true;
190 }
191
192 if (Second != ICK_Identity) {
193 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000194 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000195 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000196 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000197
198 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000199 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000200 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000201 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000202 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000203 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000204 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000205 PrintedSomething = true;
206 }
207
208 if (Third != ICK_Identity) {
209 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000210 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000211 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000212 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000213 PrintedSomething = true;
214 }
215
216 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000217 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000218 }
219}
220
221/// DebugPrint - Print this user-defined conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000224 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000225 if (Before.First || Before.Second || Before.Third) {
226 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000227 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000228 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000229 OS << "'" << ConversionFunction->getNameAsString() << "'";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000230 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000231 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000232 After.DebugPrint();
233 }
234}
235
236/// DebugPrint - Print this implicit conversion sequence to standard
237/// error. Useful for debugging overloading issues.
238void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000239 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000240 switch (ConversionKind) {
241 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000242 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000243 Standard.DebugPrint();
244 break;
245 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000246 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000247 UserDefined.DebugPrint();
248 break;
249 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000250 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000251 break;
John McCall1d318332010-01-12 00:44:57 +0000252 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000253 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000254 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000255 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000256 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000257 break;
258 }
259
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000260 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000261}
262
John McCall1d318332010-01-12 00:44:57 +0000263void AmbiguousConversionSequence::construct() {
264 new (&conversions()) ConversionSet();
265}
266
267void AmbiguousConversionSequence::destruct() {
268 conversions().~ConversionSet();
269}
270
271void
272AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
273 FromTypePtr = O.FromTypePtr;
274 ToTypePtr = O.ToTypePtr;
275 new (&conversions()) ConversionSet(O.conversions());
276}
277
278
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000279// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000280// overload of the declarations in Old. This routine returns false if
281// New and Old cannot be overloaded, e.g., if New has the same
282// signature as some function in Old (C++ 1.3.10) or if the Old
283// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000284// it does return false, MatchedDecl will point to the decl that New
285// cannot be overloaded with. This decl may be a UsingShadowDecl on
286// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000287//
288// Example: Given the following input:
289//
290// void f(int, float); // #1
291// void f(int, int); // #2
292// int f(int, int); // #3
293//
294// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000295// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000296//
John McCall51fa86f2009-12-02 08:47:38 +0000297// When we process #2, Old contains only the FunctionDecl for #1. By
298// comparing the parameter types, we see that #1 and #2 are overloaded
299// (since they have different signatures), so this routine returns
300// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000301//
John McCall51fa86f2009-12-02 08:47:38 +0000302// When we process #3, Old is an overload set containing #1 and #2. We
303// compare the signatures of #3 to #1 (they're overloaded, so we do
304// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
305// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000306// signature), IsOverload returns false and MatchedDecl will be set to
307// point to the FunctionDecl for #2.
John McCall871b2e72009-12-09 03:35:25 +0000308Sema::OverloadKind
John McCall9f54ad42009-12-10 09:41:52 +0000309Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
310 NamedDecl *&Match) {
John McCall51fa86f2009-12-02 08:47:38 +0000311 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000312 I != E; ++I) {
John McCall51fa86f2009-12-02 08:47:38 +0000313 NamedDecl *OldD = (*I)->getUnderlyingDecl();
314 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall68263142009-11-18 22:49:29 +0000315 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCall871b2e72009-12-09 03:35:25 +0000316 Match = *I;
317 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000318 }
John McCall51fa86f2009-12-02 08:47:38 +0000319 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall68263142009-11-18 22:49:29 +0000320 if (!IsOverload(New, OldF)) {
John McCall871b2e72009-12-09 03:35:25 +0000321 Match = *I;
322 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000323 }
John McCall9f54ad42009-12-10 09:41:52 +0000324 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
325 // We can overload with these, which can show up when doing
326 // redeclaration checks for UsingDecls.
327 assert(Old.getLookupKind() == LookupUsingDeclName);
328 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
329 // Optimistically assume that an unresolved using decl will
330 // overload; if it doesn't, we'll have to diagnose during
331 // template instantiation.
332 } else {
John McCall68263142009-11-18 22:49:29 +0000333 // (C++ 13p1):
334 // Only function declarations can be overloaded; object and type
335 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000336 Match = *I;
337 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000338 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000339 }
John McCall68263142009-11-18 22:49:29 +0000340
John McCall871b2e72009-12-09 03:35:25 +0000341 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000342}
343
344bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
345 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
346 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
347
348 // C++ [temp.fct]p2:
349 // A function template can be overloaded with other function templates
350 // and with normal (non-template) functions.
351 if ((OldTemplate == 0) != (NewTemplate == 0))
352 return true;
353
354 // Is the function New an overload of the function Old?
355 QualType OldQType = Context.getCanonicalType(Old->getType());
356 QualType NewQType = Context.getCanonicalType(New->getType());
357
358 // Compare the signatures (C++ 1.3.10) of the two functions to
359 // determine whether they are overloads. If we find any mismatch
360 // in the signature, they are overloads.
361
362 // If either of these functions is a K&R-style function (no
363 // prototype), then we consider them to have matching signatures.
364 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
365 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
366 return false;
367
368 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
369 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
370
371 // The signature of a function includes the types of its
372 // parameters (C++ 1.3.10), which includes the presence or absence
373 // of the ellipsis; see C++ DR 357).
374 if (OldQType != NewQType &&
375 (OldType->getNumArgs() != NewType->getNumArgs() ||
376 OldType->isVariadic() != NewType->isVariadic() ||
377 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
378 NewType->arg_type_begin())))
379 return true;
380
381 // C++ [temp.over.link]p4:
382 // The signature of a function template consists of its function
383 // signature, its return type and its template parameter list. The names
384 // of the template parameters are significant only for establishing the
385 // relationship between the template parameters and the rest of the
386 // signature.
387 //
388 // We check the return type and template parameter lists for function
389 // templates first; the remaining checks follow.
390 if (NewTemplate &&
391 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
392 OldTemplate->getTemplateParameters(),
393 false, TPL_TemplateMatch) ||
394 OldType->getResultType() != NewType->getResultType()))
395 return true;
396
397 // If the function is a class member, its signature includes the
398 // cv-qualifiers (if any) on the function itself.
399 //
400 // As part of this, also check whether one of the member functions
401 // is static, in which case they are not overloads (C++
402 // 13.1p2). While not part of the definition of the signature,
403 // this check is important to determine whether these functions
404 // can be overloaded.
405 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
406 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
407 if (OldMethod && NewMethod &&
408 !OldMethod->isStatic() && !NewMethod->isStatic() &&
409 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
410 return true;
411
412 // The signatures match; this is not an overload.
413 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000414}
415
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000416/// TryImplicitConversion - Attempt to perform an implicit conversion
417/// from the given expression (Expr) to the given type (ToType). This
418/// function returns an implicit conversion sequence that can be used
419/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000420///
421/// void f(float f);
422/// void g(int i) { f(i); }
423///
424/// this routine would produce an implicit conversion sequence to
425/// describe the initialization of f from i, which will be a standard
426/// conversion sequence containing an lvalue-to-rvalue conversion (C++
427/// 4.1) followed by a floating-integral conversion (C++ 4.9).
428//
429/// Note that this routine only determines how the conversion can be
430/// performed; it does not actually perform the conversion. As such,
431/// it will not produce any diagnostics if no conversion is available,
432/// but will instead return an implicit conversion sequence of kind
433/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000434///
435/// If @p SuppressUserConversions, then user-defined conversions are
436/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000437/// If @p AllowExplicit, then explicit user-defined conversions are
438/// permitted.
Sebastian Redle2b68332009-04-12 17:16:29 +0000439/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
440/// no matter its actual lvalueness.
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000441/// If @p UserCast, the implicit conversion is being done for a user-specified
442/// cast.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000443ImplicitConversionSequence
Anders Carlsson2974b5c2009-08-27 17:14:02 +0000444Sema::TryImplicitConversion(Expr* From, QualType ToType,
445 bool SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +0000446 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000447 bool InOverloadResolution,
448 bool UserCast) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000449 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +0000450 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall1d318332010-01-12 00:44:57 +0000451 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000452 return ICS;
453 }
454
455 if (!getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000456 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000457 return ICS;
458 }
459
460 OverloadCandidateSet Conversions(From->getExprLoc());
461 OverloadingResult UserDefResult
462 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
463 !SuppressUserConversions, AllowExplicit,
464 ForceRValue, UserCast);
465
466 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000467 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000468 // C++ [over.ics.user]p4:
469 // A conversion of an expression of class type to the same class
470 // type is given Exact Match rank, and a conversion of an
471 // expression of class type to a base class of that type is
472 // given Conversion rank, in spite of the fact that a copy
473 // constructor (i.e., a user-defined conversion function) is
474 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000475 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000476 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000477 QualType FromCanon
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000478 = Context.getCanonicalType(From->getType().getUnqualifiedType());
479 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000480 if (Constructor->isCopyConstructor() &&
Douglas Gregor0d6d12b2009-12-22 00:21:20 +0000481 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000482 // Turn this into a "standard" conversion sequence, so that it
483 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000484 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000485 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000486 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000487 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000488 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000489 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000490 ICS.Standard.Second = ICK_Derived_To_Base;
491 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000492 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000493
494 // C++ [over.best.ics]p4:
495 // However, when considering the argument of a user-defined
496 // conversion function that is a candidate by 13.3.1.3 when
497 // invoked for the copying of the temporary in the second step
498 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
499 // 13.3.1.6 in all cases, only standard conversion sequences and
500 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000501 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000502 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000503 }
John McCallcefd3ad2010-01-13 22:30:33 +0000504 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000505 ICS.setAmbiguous();
506 ICS.Ambiguous.setFromType(From->getType());
507 ICS.Ambiguous.setToType(ToType);
508 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
509 Cand != Conversions.end(); ++Cand)
510 if (Cand->Viable)
511 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000512 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000513 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000514 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000515
516 return ICS;
517}
518
Douglas Gregor43c79c22009-12-09 00:47:37 +0000519/// \brief Determine whether the conversion from FromType to ToType is a valid
520/// conversion that strips "noreturn" off the nested function type.
521static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
522 QualType ToType, QualType &ResultTy) {
523 if (Context.hasSameUnqualifiedType(FromType, ToType))
524 return false;
525
526 // Strip the noreturn off the type we're converting from; noreturn can
527 // safely be removed.
528 FromType = Context.getNoReturnType(FromType, false);
529 if (!Context.hasSameUnqualifiedType(FromType, ToType))
530 return false;
531
532 ResultTy = FromType;
533 return true;
534}
535
Douglas Gregor60d62c22008-10-31 16:23:19 +0000536/// IsStandardConversion - Determines whether there is a standard
537/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
538/// expression From to the type ToType. Standard conversion sequences
539/// only consider non-class types; for conversions that involve class
540/// types, use TryImplicitConversion. If a conversion exists, SCS will
541/// contain the standard conversion sequence required to perform this
542/// conversion and this routine will return true. Otherwise, this
543/// routine will return false and the value of SCS is unspecified.
Mike Stump1eb44332009-09-09 15:08:12 +0000544bool
545Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000546 bool InOverloadResolution,
Mike Stump1eb44332009-09-09 15:08:12 +0000547 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000548 QualType FromType = From->getType();
549
Douglas Gregor60d62c22008-10-31 16:23:19 +0000550 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000551 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +0000552 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000553 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +0000554 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000555 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000556
Douglas Gregorf9201e02009-02-11 23:02:49 +0000557 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000558 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000559 if (FromType->isRecordType() || ToType->isRecordType()) {
560 if (getLangOptions().CPlusPlus)
561 return false;
562
Mike Stump1eb44332009-09-09 15:08:12 +0000563 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000564 }
565
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000566 // The first conversion can be an lvalue-to-rvalue conversion,
567 // array-to-pointer conversion, or function-to-pointer conversion
568 // (C++ 4p1).
569
John McCall6bb80172010-03-30 21:47:33 +0000570 DeclAccessPair AccessPair;
571
Mike Stump1eb44332009-09-09 15:08:12 +0000572 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000573 // An lvalue (3.10) of a non-function, non-array type T can be
574 // converted to an rvalue.
575 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000576 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000577 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000578 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000579 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000580
581 // If T is a non-class type, the type of the rvalue is the
582 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000583 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
584 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000585 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000586 } else if (FromType->isArrayType()) {
587 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000588 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000589
590 // An lvalue or rvalue of type "array of N T" or "array of unknown
591 // bound of T" can be converted to an rvalue of type "pointer to
592 // T" (C++ 4.2p1).
593 FromType = Context.getArrayDecayedType(FromType);
594
595 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
596 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +0000597 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000598
599 // For the purpose of ranking in overload resolution
600 // (13.3.3.1.1), this conversion is considered an
601 // array-to-pointer conversion followed by a qualification
602 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000603 SCS.Second = ICK_Identity;
604 SCS.Third = ICK_Qualification;
Douglas Gregorad323a82010-01-27 03:51:04 +0000605 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000606 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000607 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000608 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
609 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000610 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000611
612 // An lvalue of function type T can be converted to an rvalue of
613 // type "pointer to T." The result is a pointer to the
614 // function. (C++ 4.3p1).
615 FromType = Context.getPointerType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000616 } else if (FunctionDecl *Fn
John McCall6bb80172010-03-30 21:47:33 +0000617 = ResolveAddressOfOverloadedFunction(From, ToType, false,
618 AccessPair)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000619 // Address of overloaded function (C++ [over.over]).
Douglas Gregor904eed32008-11-10 20:40:00 +0000620 SCS.First = ICK_Function_To_Pointer;
621
622 // We were able to resolve the address of the overloaded function,
623 // so we can convert to the type of that function.
624 FromType = Fn->getType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000625 if (ToType->isLValueReferenceType())
626 FromType = Context.getLValueReferenceType(FromType);
627 else if (ToType->isRValueReferenceType())
628 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000629 else if (ToType->isMemberPointerType()) {
630 // Resolve address only succeeds if both sides are member pointers,
631 // but it doesn't have to be the same class. See DR 247.
632 // Note that this means that the type of &Derived::fn can be
633 // Ret (Base::*)(Args) if the fn overload actually found is from the
634 // base class, even if it was brought into the derived class via a
635 // using declaration. The standard isn't clear on this issue at all.
636 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
637 FromType = Context.getMemberPointerType(FromType,
638 Context.getTypeDeclType(M->getParent()).getTypePtr());
639 } else
Douglas Gregor904eed32008-11-10 20:40:00 +0000640 FromType = Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000641 } else {
642 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000643 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000644 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000645 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000646
647 // The second conversion can be an integral promotion, floating
648 // point promotion, integral conversion, floating point conversion,
649 // floating-integral conversion, pointer conversion,
650 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000651 // For overloading in C, this can also be a "compatible-type"
652 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000653 bool IncompatibleObjC = false;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000654 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000655 // The unqualified versions of the types are the same: there's no
656 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000657 SCS.Second = ICK_Identity;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000658 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000659 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000660 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000661 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000662 } else if (IsFloatingPointPromotion(FromType, ToType)) {
663 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000664 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000665 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000666 } else if (IsComplexPromotion(FromType, ToType)) {
667 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000668 SCS.Second = ICK_Complex_Promotion;
669 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000670 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000671 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000672 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000673 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000674 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000675 } else if (FromType->isComplexType() && ToType->isComplexType()) {
676 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000677 SCS.Second = ICK_Complex_Conversion;
678 FromType = ToType.getUnqualifiedType();
Chandler Carruth23a370f2010-02-25 07:20:54 +0000679 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
680 (ToType->isComplexType() && FromType->isArithmeticType())) {
681 // Complex-real conversions (C99 6.3.1.7)
682 SCS.Second = ICK_Complex_Real;
683 FromType = ToType.getUnqualifiedType();
684 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
685 // Floating point conversions (C++ 4.8).
686 SCS.Second = ICK_Floating_Conversion;
687 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000688 } else if ((FromType->isFloatingType() &&
689 ToType->isIntegralType() && (!ToType->isBooleanType() &&
690 !ToType->isEnumeralType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000691 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000692 ToType->isFloatingType())) {
693 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000694 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000695 FromType = ToType.getUnqualifiedType();
Anders Carlsson08972922009-08-28 15:33:32 +0000696 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
697 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000698 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000699 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000700 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregorce940492009-09-25 04:25:58 +0000701 } else if (IsMemberPointerConversion(From, FromType, ToType,
702 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000703 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000704 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000705 } else if (ToType->isBooleanType() &&
706 (FromType->isArithmeticType() ||
707 FromType->isEnumeralType() ||
Fariborz Jahanian1f7711d2009-12-11 21:23:13 +0000708 FromType->isAnyPointerType() ||
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000709 FromType->isBlockPointerType() ||
710 FromType->isMemberPointerType() ||
711 FromType->isNullPtrType())) {
712 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000713 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000714 FromType = Context.BoolTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000715 } else if (!getLangOptions().CPlusPlus &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000716 Context.typesAreCompatible(ToType, FromType)) {
717 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000718 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor43c79c22009-12-09 00:47:37 +0000719 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
720 // Treat a conversion that strips "noreturn" as an identity conversion.
721 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000722 } else {
723 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000724 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000725 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000726 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000727
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000728 QualType CanonFrom;
729 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000730 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000731 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000732 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000733 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000734 CanonFrom = Context.getCanonicalType(FromType);
735 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000736 } else {
737 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000738 SCS.Third = ICK_Identity;
739
Mike Stump1eb44332009-09-09 15:08:12 +0000740 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +0000741 // [...] Any difference in top-level cv-qualification is
742 // subsumed by the initialization itself and does not constitute
743 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000744 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000745 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +0000746 if (CanonFrom.getLocalUnqualifiedType()
747 == CanonTo.getLocalUnqualifiedType() &&
748 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000749 FromType = ToType;
750 CanonFrom = CanonTo;
751 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000752 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000753 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000754
755 // If we have not converted the argument type to the parameter type,
756 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000757 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000758 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000759
Douglas Gregor60d62c22008-10-31 16:23:19 +0000760 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000761}
762
763/// IsIntegralPromotion - Determines whether the conversion from the
764/// expression From (whose potentially-adjusted type is FromType) to
765/// ToType is an integral promotion (C++ 4.5). If so, returns true and
766/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000767bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000768 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000769 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000770 if (!To) {
771 return false;
772 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000773
774 // An rvalue of type char, signed char, unsigned char, short int, or
775 // unsigned short int can be converted to an rvalue of type int if
776 // int can represent all the values of the source type; otherwise,
777 // the source rvalue can be converted to an rvalue of type unsigned
778 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +0000779 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
780 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000781 if (// We can promote any signed, promotable integer type to an int
782 (FromType->isSignedIntegerType() ||
783 // We can promote any unsigned integer type whose size is
784 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +0000785 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000786 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000787 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000788 }
789
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000790 return To->getKind() == BuiltinType::UInt;
791 }
792
793 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
794 // can be converted to an rvalue of the first of the following types
795 // that can represent all the values of its underlying type: int,
796 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall842aef82009-12-09 09:09:27 +0000797
798 // We pre-calculate the promotion type for enum types.
799 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
800 if (ToType->isIntegerType())
801 return Context.hasSameUnqualifiedType(ToType,
802 FromEnumType->getDecl()->getPromotionType());
803
804 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000805 // Determine whether the type we're converting from is signed or
806 // unsigned.
807 bool FromIsSigned;
808 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +0000809
810 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
811 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000812
813 // The types we'll try to promote to, in the appropriate
814 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +0000815 QualType PromoteTypes[6] = {
816 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000817 Context.LongTy, Context.UnsignedLongTy ,
818 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000819 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000820 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000821 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
822 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +0000823 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000824 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
825 // We found the type that we can promote to. If this is the
826 // type we wanted, we have a promotion. Otherwise, no
827 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000828 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000829 }
830 }
831 }
832
833 // An rvalue for an integral bit-field (9.6) can be converted to an
834 // rvalue of type int if int can represent all the values of the
835 // bit-field; otherwise, it can be converted to unsigned int if
836 // unsigned int can represent all the values of the bit-field. If
837 // the bit-field is larger yet, no integral promotion applies to
838 // it. If the bit-field has an enumerated type, it is treated as any
839 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +0000840 // FIXME: We should delay checking of bit-fields until we actually perform the
841 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000842 using llvm::APSInt;
843 if (From)
844 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +0000845 APSInt BitWidth;
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000846 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
847 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
848 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
849 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Douglas Gregor86f19402008-12-20 23:49:58 +0000851 // Are we promoting to an int from a bitfield that fits in an int?
852 if (BitWidth < ToSize ||
853 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
854 return To->getKind() == BuiltinType::Int;
855 }
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Douglas Gregor86f19402008-12-20 23:49:58 +0000857 // Are we promoting to an unsigned int from an unsigned bitfield
858 // that fits into an unsigned int?
859 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
860 return To->getKind() == BuiltinType::UInt;
861 }
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Douglas Gregor86f19402008-12-20 23:49:58 +0000863 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000864 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000865 }
Mike Stump1eb44332009-09-09 15:08:12 +0000866
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000867 // An rvalue of type bool can be converted to an rvalue of type int,
868 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000869 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000870 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000871 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000872
873 return false;
874}
875
876/// IsFloatingPointPromotion - Determines whether the conversion from
877/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
878/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000879bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000880 /// An rvalue of type float can be converted to an rvalue of type
881 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +0000882 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
883 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000884 if (FromBuiltin->getKind() == BuiltinType::Float &&
885 ToBuiltin->getKind() == BuiltinType::Double)
886 return true;
887
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000888 // C99 6.3.1.5p1:
889 // When a float is promoted to double or long double, or a
890 // double is promoted to long double [...].
891 if (!getLangOptions().CPlusPlus &&
892 (FromBuiltin->getKind() == BuiltinType::Float ||
893 FromBuiltin->getKind() == BuiltinType::Double) &&
894 (ToBuiltin->getKind() == BuiltinType::LongDouble))
895 return true;
896 }
897
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000898 return false;
899}
900
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000901/// \brief Determine if a conversion is a complex promotion.
902///
903/// A complex promotion is defined as a complex -> complex conversion
904/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000905/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000906bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000907 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000908 if (!FromComplex)
909 return false;
910
John McCall183700f2009-09-21 23:43:11 +0000911 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000912 if (!ToComplex)
913 return false;
914
915 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000916 ToComplex->getElementType()) ||
917 IsIntegralPromotion(0, FromComplex->getElementType(),
918 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000919}
920
Douglas Gregorcb7de522008-11-26 23:31:11 +0000921/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
922/// the pointer type FromPtr to a pointer to type ToPointee, with the
923/// same type qualifiers as FromPtr has on its pointee type. ToType,
924/// if non-empty, will be a pointer to ToType that may or may not have
925/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +0000926static QualType
927BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000928 QualType ToPointee, QualType ToType,
929 ASTContext &Context) {
930 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
931 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +0000932 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +0000933
934 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000935 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +0000936 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +0000937 if (!ToType.isNull())
Douglas Gregorcb7de522008-11-26 23:31:11 +0000938 return ToType;
939
940 // Build a pointer to ToPointee. It has the right qualifiers
941 // already.
942 return Context.getPointerType(ToPointee);
943 }
944
945 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +0000946 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +0000947 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
948 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +0000949}
950
Fariborz Jahanianadcfab12009-12-16 23:13:33 +0000951/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
952/// the FromType, which is an objective-c pointer, to ToType, which may or may
953/// not have the right set of qualifiers.
954static QualType
955BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
956 QualType ToType,
957 ASTContext &Context) {
958 QualType CanonFromType = Context.getCanonicalType(FromType);
959 QualType CanonToType = Context.getCanonicalType(ToType);
960 Qualifiers Quals = CanonFromType.getQualifiers();
961
962 // Exact qualifier match -> return the pointer type we're converting to.
963 if (CanonToType.getLocalQualifiers() == Quals)
964 return ToType;
965
966 // Just build a canonical type that has the right qualifiers.
967 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
968}
969
Mike Stump1eb44332009-09-09 15:08:12 +0000970static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000971 bool InOverloadResolution,
972 ASTContext &Context) {
973 // Handle value-dependent integral null pointer constants correctly.
974 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
975 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
976 Expr->getType()->isIntegralType())
977 return !InOverloadResolution;
978
Douglas Gregorce940492009-09-25 04:25:58 +0000979 return Expr->isNullPointerConstant(Context,
980 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
981 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000982}
Mike Stump1eb44332009-09-09 15:08:12 +0000983
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000984/// IsPointerConversion - Determines whether the conversion of the
985/// expression From, which has the (possibly adjusted) type FromType,
986/// can be converted to the type ToType via a pointer conversion (C++
987/// 4.10). If so, returns true and places the converted type (that
988/// might differ from ToType in its cv-qualifiers at some level) into
989/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000990///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000991/// This routine also supports conversions to and from block pointers
992/// and conversions with Objective-C's 'id', 'id<protocols...>', and
993/// pointers to interfaces. FIXME: Once we've determined the
994/// appropriate overloading rules for Objective-C, we may want to
995/// split the Objective-C checks into a different routine; however,
996/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000997/// conversions, so for now they live here. IncompatibleObjC will be
998/// set if the conversion is an allowed Objective-C conversion that
999/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001000bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001001 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001002 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001003 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001004 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +00001005 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1006 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001007
Mike Stump1eb44332009-09-09 15:08:12 +00001008 // Conversion from a null pointer constant to any Objective-C pointer type.
1009 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001010 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001011 ConvertedType = ToType;
1012 return true;
1013 }
1014
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001015 // Blocks: Block pointers can be converted to void*.
1016 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001017 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001018 ConvertedType = ToType;
1019 return true;
1020 }
1021 // Blocks: A null pointer constant can be converted to a block
1022 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001023 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001024 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001025 ConvertedType = ToType;
1026 return true;
1027 }
1028
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001029 // If the left-hand-side is nullptr_t, the right side can be a null
1030 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001031 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001032 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001033 ConvertedType = ToType;
1034 return true;
1035 }
1036
Ted Kremenek6217b802009-07-29 21:53:49 +00001037 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001038 if (!ToTypePtr)
1039 return false;
1040
1041 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001042 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001043 ConvertedType = ToType;
1044 return true;
1045 }
Sebastian Redl07779722008-10-31 14:43:28 +00001046
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001047 // Beyond this point, both types need to be pointers
1048 // , including objective-c pointers.
1049 QualType ToPointeeType = ToTypePtr->getPointeeType();
1050 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1051 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1052 ToType, Context);
1053 return true;
1054
1055 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001056 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001057 if (!FromTypePtr)
1058 return false;
1059
1060 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001061
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001062 // An rvalue of type "pointer to cv T," where T is an object type,
1063 // can be converted to an rvalue of type "pointer to cv void" (C++
1064 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +00001065 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001066 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001067 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001068 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001069 return true;
1070 }
1071
Douglas Gregorf9201e02009-02-11 23:02:49 +00001072 // When we're overloading in C, we allow a special kind of pointer
1073 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001074 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001075 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001076 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001077 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001078 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001079 return true;
1080 }
1081
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001082 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001083 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001084 // An rvalue of type "pointer to cv D," where D is a class type,
1085 // can be converted to an rvalue of type "pointer to cv B," where
1086 // B is a base class (clause 10) of D. If B is an inaccessible
1087 // (clause 11) or ambiguous (10.2) base class of D, a program that
1088 // necessitates this conversion is ill-formed. The result of the
1089 // conversion is a pointer to the base class sub-object of the
1090 // derived class object. The null pointer value is converted to
1091 // the null pointer value of the destination type.
1092 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001093 // Note that we do not check for ambiguity or inaccessibility
1094 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001095 if (getLangOptions().CPlusPlus &&
1096 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001097 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001098 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001099 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001100 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001101 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001102 ToType, Context);
1103 return true;
1104 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001105
Douglas Gregorc7887512008-12-19 19:13:09 +00001106 return false;
1107}
1108
1109/// isObjCPointerConversion - Determines whether this is an
1110/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1111/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001112bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001113 QualType& ConvertedType,
1114 bool &IncompatibleObjC) {
1115 if (!getLangOptions().ObjC1)
1116 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001117
Steve Naroff14108da2009-07-10 23:34:53 +00001118 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001119 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001120 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001121 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001122
Steve Naroff14108da2009-07-10 23:34:53 +00001123 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001124 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001125 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001126 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001127 ConvertedType = ToType;
1128 return true;
1129 }
1130 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001131 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001132 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001133 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001134 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001135 ConvertedType = ToType;
1136 return true;
1137 }
1138 // Objective C++: We're able to convert from a pointer to an
1139 // interface to a pointer to a different interface.
1140 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001141 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1142 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1143 if (getLangOptions().CPlusPlus && LHS && RHS &&
1144 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1145 FromObjCPtr->getPointeeType()))
1146 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00001147 ConvertedType = ToType;
1148 return true;
1149 }
1150
1151 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1152 // Okay: this is some kind of implicit downcast of Objective-C
1153 // interfaces, which is permitted. However, we're going to
1154 // complain about it.
1155 IncompatibleObjC = true;
1156 ConvertedType = FromType;
1157 return true;
1158 }
Mike Stump1eb44332009-09-09 15:08:12 +00001159 }
Steve Naroff14108da2009-07-10 23:34:53 +00001160 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001161 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001162 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001163 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001164 else if (const BlockPointerType *ToBlockPtr =
1165 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001166 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001167 // to a block pointer type.
1168 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1169 ConvertedType = ToType;
1170 return true;
1171 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001172 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001173 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001174 else if (FromType->getAs<BlockPointerType>() &&
1175 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1176 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001177 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001178 ConvertedType = ToType;
1179 return true;
1180 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001181 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001182 return false;
1183
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001184 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001185 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001186 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001187 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001188 FromPointeeType = FromBlockPtr->getPointeeType();
1189 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001190 return false;
1191
Douglas Gregorc7887512008-12-19 19:13:09 +00001192 // If we have pointers to pointers, recursively check whether this
1193 // is an Objective-C conversion.
1194 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1195 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1196 IncompatibleObjC)) {
1197 // We always complain about this conversion.
1198 IncompatibleObjC = true;
1199 ConvertedType = ToType;
1200 return true;
1201 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001202 // Allow conversion of pointee being objective-c pointer to another one;
1203 // as in I* to id.
1204 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1205 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1206 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1207 IncompatibleObjC)) {
1208 ConvertedType = ToType;
1209 return true;
1210 }
1211
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001212 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001213 // differences in the argument and result types are in Objective-C
1214 // pointer conversions. If so, we permit the conversion (but
1215 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001216 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001217 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001218 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001219 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001220 if (FromFunctionType && ToFunctionType) {
1221 // If the function types are exactly the same, this isn't an
1222 // Objective-C pointer conversion.
1223 if (Context.getCanonicalType(FromPointeeType)
1224 == Context.getCanonicalType(ToPointeeType))
1225 return false;
1226
1227 // Perform the quick checks that will tell us whether these
1228 // function types are obviously different.
1229 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1230 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1231 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1232 return false;
1233
1234 bool HasObjCConversion = false;
1235 if (Context.getCanonicalType(FromFunctionType->getResultType())
1236 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1237 // Okay, the types match exactly. Nothing to do.
1238 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1239 ToFunctionType->getResultType(),
1240 ConvertedType, IncompatibleObjC)) {
1241 // Okay, we have an Objective-C pointer conversion.
1242 HasObjCConversion = true;
1243 } else {
1244 // Function types are too different. Abort.
1245 return false;
1246 }
Mike Stump1eb44332009-09-09 15:08:12 +00001247
Douglas Gregorc7887512008-12-19 19:13:09 +00001248 // Check argument types.
1249 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1250 ArgIdx != NumArgs; ++ArgIdx) {
1251 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1252 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1253 if (Context.getCanonicalType(FromArgType)
1254 == Context.getCanonicalType(ToArgType)) {
1255 // Okay, the types match exactly. Nothing to do.
1256 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1257 ConvertedType, IncompatibleObjC)) {
1258 // Okay, we have an Objective-C pointer conversion.
1259 HasObjCConversion = true;
1260 } else {
1261 // Argument types are too different. Abort.
1262 return false;
1263 }
1264 }
1265
1266 if (HasObjCConversion) {
1267 // We had an Objective-C conversion. Allow this pointer
1268 // conversion, but complain about it.
1269 ConvertedType = ToType;
1270 IncompatibleObjC = true;
1271 return true;
1272 }
1273 }
1274
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001275 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001276}
1277
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001278/// CheckPointerConversion - Check the pointer conversion from the
1279/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001280/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001281/// conversions for which IsPointerConversion has already returned
1282/// true. It returns true and produces a diagnostic if there was an
1283/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001284bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001285 CastExpr::CastKind &Kind,
1286 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001287 QualType FromType = From->getType();
1288
Ted Kremenek6217b802009-07-29 21:53:49 +00001289 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1290 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001291 QualType FromPointeeType = FromPtrType->getPointeeType(),
1292 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001293
Douglas Gregor5fccd362010-03-03 23:55:11 +00001294 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1295 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001296 // We must have a derived-to-base conversion. Check an
1297 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001298 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1299 From->getExprLoc(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001300 From->getSourceRange(),
1301 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001302 return true;
1303
1304 // The conversion was successful.
1305 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001306 }
1307 }
Mike Stump1eb44332009-09-09 15:08:12 +00001308 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001309 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001310 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001311 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001312 // Objective-C++ conversions are always okay.
1313 // FIXME: We should have a different class of conversions for the
1314 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001315 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001316 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001317
Steve Naroff14108da2009-07-10 23:34:53 +00001318 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001319 return false;
1320}
1321
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001322/// IsMemberPointerConversion - Determines whether the conversion of the
1323/// expression From, which has the (possibly adjusted) type FromType, can be
1324/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1325/// If so, returns true and places the converted type (that might differ from
1326/// ToType in its cv-qualifiers at some level) into ConvertedType.
1327bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001328 QualType ToType,
1329 bool InOverloadResolution,
1330 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001331 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001332 if (!ToTypePtr)
1333 return false;
1334
1335 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001336 if (From->isNullPointerConstant(Context,
1337 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1338 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001339 ConvertedType = ToType;
1340 return true;
1341 }
1342
1343 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001344 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001345 if (!FromTypePtr)
1346 return false;
1347
1348 // A pointer to member of B can be converted to a pointer to member of D,
1349 // where D is derived from B (C++ 4.11p2).
1350 QualType FromClass(FromTypePtr->getClass(), 0);
1351 QualType ToClass(ToTypePtr->getClass(), 0);
1352 // FIXME: What happens when these are dependent? Is this function even called?
1353
1354 if (IsDerivedFrom(ToClass, FromClass)) {
1355 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1356 ToClass.getTypePtr());
1357 return true;
1358 }
1359
1360 return false;
1361}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001362
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001363/// CheckMemberPointerConversion - Check the member pointer conversion from the
1364/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00001365/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001366/// for which IsMemberPointerConversion has already returned true. It returns
1367/// true and produces a diagnostic if there was an error, or returns false
1368/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001369bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001370 CastExpr::CastKind &Kind,
1371 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001372 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001373 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001374 if (!FromPtrType) {
1375 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001376 assert(From->isNullPointerConstant(Context,
1377 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001378 "Expr must be null pointer constant!");
1379 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001380 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001381 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001382
Ted Kremenek6217b802009-07-29 21:53:49 +00001383 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001384 assert(ToPtrType && "No member pointer cast has a target type "
1385 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001386
Sebastian Redl21593ac2009-01-28 18:33:18 +00001387 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1388 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001389
Sebastian Redl21593ac2009-01-28 18:33:18 +00001390 // FIXME: What about dependent types?
1391 assert(FromClass->isRecordType() && "Pointer into non-class.");
1392 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001393
John McCall6b2accb2010-02-10 09:31:12 +00001394 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/ true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001395 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001396 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1397 assert(DerivationOkay &&
1398 "Should not have been called if derivation isn't OK.");
1399 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001400
Sebastian Redl21593ac2009-01-28 18:33:18 +00001401 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1402 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001403 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1404 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1405 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1406 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001407 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001408
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001409 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001410 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1411 << FromClass << ToClass << QualType(VBase, 0)
1412 << From->getSourceRange();
1413 return true;
1414 }
1415
John McCall6b2accb2010-02-10 09:31:12 +00001416 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00001417 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1418 Paths.front(),
1419 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00001420
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001421 // Must be a base to derived member conversion.
1422 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001423 return false;
1424}
1425
Douglas Gregor98cd5992008-10-21 23:43:52 +00001426/// IsQualificationConversion - Determines whether the conversion from
1427/// an rvalue of type FromType to ToType is a qualification conversion
1428/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001429bool
1430Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001431 FromType = Context.getCanonicalType(FromType);
1432 ToType = Context.getCanonicalType(ToType);
1433
1434 // If FromType and ToType are the same type, this is not a
1435 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00001436 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00001437 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001438
Douglas Gregor98cd5992008-10-21 23:43:52 +00001439 // (C++ 4.4p4):
1440 // A conversion can add cv-qualifiers at levels other than the first
1441 // in multi-level pointers, subject to the following rules: [...]
1442 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001443 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001444 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001445 // Within each iteration of the loop, we check the qualifiers to
1446 // determine if this still looks like a qualification
1447 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001448 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001449 // until there are no more pointers or pointers-to-members left to
1450 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001451 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001452
1453 // -- for every j > 0, if const is in cv 1,j then const is in cv
1454 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001455 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001456 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001457
Douglas Gregor98cd5992008-10-21 23:43:52 +00001458 // -- if the cv 1,j and cv 2,j are different, then const is in
1459 // every cv for 0 < k < j.
1460 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001461 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001462 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Douglas Gregor98cd5992008-10-21 23:43:52 +00001464 // Keep track of whether all prior cv-qualifiers in the "to" type
1465 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001466 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001467 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001468 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001469
1470 // We are left with FromType and ToType being the pointee types
1471 // after unwrapping the original FromType and ToType the same number
1472 // of types. If we unwrapped any pointers, and if FromType and
1473 // ToType have the same unqualified type (since we checked
1474 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001475 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001476}
1477
Douglas Gregor734d9862009-01-30 23:27:23 +00001478/// Determines whether there is a user-defined conversion sequence
1479/// (C++ [over.ics.user]) that converts expression From to the type
1480/// ToType. If such a conversion exists, User will contain the
1481/// user-defined conversion sequence that performs such a conversion
1482/// and this routine will return true. Otherwise, this routine returns
1483/// false and User is unspecified.
1484///
1485/// \param AllowConversionFunctions true if the conversion should
1486/// consider conversion functions at all. If false, only constructors
1487/// will be considered.
1488///
1489/// \param AllowExplicit true if the conversion should consider C++0x
1490/// "explicit" conversion functions as well as non-explicit conversion
1491/// functions (C++0x [class.conv.fct]p2).
Sebastian Redle2b68332009-04-12 17:16:29 +00001492///
1493/// \param ForceRValue true if the expression should be treated as an rvalue
1494/// for overload resolution.
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001495/// \param UserCast true if looking for user defined conversion for a static
1496/// cast.
Douglas Gregor20093b42009-12-09 23:02:17 +00001497OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1498 UserDefinedConversionSequence& User,
1499 OverloadCandidateSet& CandidateSet,
1500 bool AllowConversionFunctions,
1501 bool AllowExplicit,
1502 bool ForceRValue,
1503 bool UserCast) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001504 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00001505 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1506 // We're not going to find any constructors.
1507 } else if (CXXRecordDecl *ToRecordDecl
1508 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001509 // C++ [over.match.ctor]p1:
1510 // When objects of class type are direct-initialized (8.5), or
1511 // copy-initialized from an expression of the same or a
1512 // derived class type (8.5), overload resolution selects the
1513 // constructor. [...] For copy-initialization, the candidate
1514 // functions are all the converting constructors (12.3.1) of
1515 // that class. The argument list is the expression-list within
1516 // the parentheses of the initializer.
Douglas Gregor79b680e2009-11-13 18:44:21 +00001517 bool SuppressUserConversions = !UserCast;
1518 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1519 IsDerivedFrom(From->getType(), ToType)) {
1520 SuppressUserConversions = false;
1521 AllowConversionFunctions = false;
1522 }
1523
Mike Stump1eb44332009-09-09 15:08:12 +00001524 DeclarationName ConstructorName
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001525 = Context.DeclarationNames.getCXXConstructorName(
1526 Context.getCanonicalType(ToType).getUnqualifiedType());
1527 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump1eb44332009-09-09 15:08:12 +00001528 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001529 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001530 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00001531 NamedDecl *D = *Con;
1532 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1533
Douglas Gregordec06662009-08-21 18:42:58 +00001534 // Find the constructor (which may be a template).
1535 CXXConstructorDecl *Constructor = 0;
1536 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00001537 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00001538 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001539 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001540 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1541 else
John McCall9aa472c2010-03-19 07:35:19 +00001542 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001543
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001544 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001545 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001546 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00001547 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001548 /*ExplicitArgs*/ 0,
John McCalld5532b62009-11-23 01:53:49 +00001549 &From, 1, CandidateSet,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001550 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001551 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001552 // Allow one user-defined conversion when user specifies a
1553 // From->ToType conversion via an static cast (c-style, etc).
John McCall9aa472c2010-03-19 07:35:19 +00001554 AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001555 &From, 1, CandidateSet,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001556 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001557 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001558 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001559 }
1560 }
1561
Douglas Gregor734d9862009-01-30 23:27:23 +00001562 if (!AllowConversionFunctions) {
1563 // Don't allow any conversion functions to enter the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00001564 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1565 PDiag(0)
Anders Carlssonb7906612009-08-26 23:45:07 +00001566 << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001567 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001568 } else if (const RecordType *FromRecordType
Ted Kremenek6217b802009-07-29 21:53:49 +00001569 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001570 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001571 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1572 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00001573 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001574 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001575 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001576 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00001577 DeclAccessPair FoundDecl = I.getPair();
1578 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00001579 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1580 if (isa<UsingShadowDecl>(D))
1581 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1582
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001583 CXXConversionDecl *Conv;
1584 FunctionTemplateDecl *ConvTemplate;
John McCallba135432009-11-21 08:51:07 +00001585 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001586 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1587 else
John McCallba135432009-11-21 08:51:07 +00001588 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001589
1590 if (AllowExplicit || !Conv->isExplicit()) {
1591 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00001592 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001593 ActingContext, From, ToType,
1594 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001595 else
John McCall9aa472c2010-03-19 07:35:19 +00001596 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCall86820f52010-01-26 01:37:31 +00001597 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001598 }
1599 }
1600 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001601 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001602
1603 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001604 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001605 case OR_Success:
1606 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001607 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001608 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1609 // C++ [over.ics.user]p1:
1610 // If the user-defined conversion is specified by a
1611 // constructor (12.3.1), the initial standard conversion
1612 // sequence converts the source type to the type required by
1613 // the argument of the constructor.
1614 //
Douglas Gregor60d62c22008-10-31 16:23:19 +00001615 QualType ThisType = Constructor->getThisType(Context);
John McCall1d318332010-01-12 00:44:57 +00001616 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001617 User.EllipsisConversion = true;
1618 else {
1619 User.Before = Best->Conversions[0].Standard;
1620 User.EllipsisConversion = false;
1621 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001622 User.ConversionFunction = Constructor;
1623 User.After.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00001624 User.After.setFromType(
1625 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregorad323a82010-01-27 03:51:04 +00001626 User.After.setAllToTypes(ToType);
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001627 return OR_Success;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001628 } else if (CXXConversionDecl *Conversion
1629 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1630 // C++ [over.ics.user]p1:
1631 //
1632 // [...] If the user-defined conversion is specified by a
1633 // conversion function (12.3.2), the initial standard
1634 // conversion sequence converts the source type to the
1635 // implicit object parameter of the conversion function.
1636 User.Before = Best->Conversions[0].Standard;
1637 User.ConversionFunction = Conversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001638 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001639
1640 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001641 // The second standard conversion sequence converts the
1642 // result of the user-defined conversion to the target type
1643 // for the sequence. Since an implicit conversion sequence
1644 // is an initialization, the special rules for
1645 // initialization by user-defined conversion apply when
1646 // selecting the best user-defined conversion for a
1647 // user-defined conversion sequence (see 13.3.3 and
1648 // 13.3.3.1).
1649 User.After = Best->FinalConversion;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001650 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001651 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001652 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001653 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001654 }
Mike Stump1eb44332009-09-09 15:08:12 +00001655
Douglas Gregor60d62c22008-10-31 16:23:19 +00001656 case OR_No_Viable_Function:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001657 return OR_No_Viable_Function;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001658 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001659 // No conversion here! We're done.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001660 return OR_Deleted;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001661
1662 case OR_Ambiguous:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001663 return OR_Ambiguous;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001664 }
1665
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001666 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001667}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001668
1669bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001670Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001671 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00001672 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001673 OverloadingResult OvResult =
1674 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1675 CandidateSet, true, false, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001676 if (OvResult == OR_Ambiguous)
1677 Diag(From->getSourceRange().getBegin(),
1678 diag::err_typecheck_ambiguous_condition)
1679 << From->getType() << ToType << From->getSourceRange();
1680 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1681 Diag(From->getSourceRange().getBegin(),
1682 diag::err_typecheck_nonviable_condition)
1683 << From->getType() << ToType << From->getSourceRange();
1684 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001685 return false;
John McCallcbce6062010-01-12 07:18:19 +00001686 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001687 return true;
1688}
Douglas Gregor60d62c22008-10-31 16:23:19 +00001689
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001690/// CompareImplicitConversionSequences - Compare two implicit
1691/// conversion sequences to determine whether one is better than the
1692/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00001693ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001694Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1695 const ImplicitConversionSequence& ICS2)
1696{
1697 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1698 // conversion sequences (as defined in 13.3.3.1)
1699 // -- a standard conversion sequence (13.3.3.1.1) is a better
1700 // conversion sequence than a user-defined conversion sequence or
1701 // an ellipsis conversion sequence, and
1702 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1703 // conversion sequence than an ellipsis conversion sequence
1704 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00001705 //
John McCall1d318332010-01-12 00:44:57 +00001706 // C++0x [over.best.ics]p10:
1707 // For the purpose of ranking implicit conversion sequences as
1708 // described in 13.3.3.2, the ambiguous conversion sequence is
1709 // treated as a user-defined sequence that is indistinguishable
1710 // from any other user-defined conversion sequence.
1711 if (ICS1.getKind() < ICS2.getKind()) {
1712 if (!(ICS1.isUserDefined() && ICS2.isAmbiguous()))
1713 return ImplicitConversionSequence::Better;
1714 } else if (ICS2.getKind() < ICS1.getKind()) {
1715 if (!(ICS2.isUserDefined() && ICS1.isAmbiguous()))
1716 return ImplicitConversionSequence::Worse;
1717 }
1718
1719 if (ICS1.isAmbiguous() || ICS2.isAmbiguous())
1720 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001721
1722 // Two implicit conversion sequences of the same form are
1723 // indistinguishable conversion sequences unless one of the
1724 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00001725 if (ICS1.isStandard())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001726 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00001727 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001728 // User-defined conversion sequence U1 is a better conversion
1729 // sequence than another user-defined conversion sequence U2 if
1730 // they contain the same user-defined conversion function or
1731 // constructor and if the second standard conversion sequence of
1732 // U1 is better than the second standard conversion sequence of
1733 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001734 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001735 ICS2.UserDefined.ConversionFunction)
1736 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1737 ICS2.UserDefined.After);
1738 }
1739
1740 return ImplicitConversionSequence::Indistinguishable;
1741}
1742
Douglas Gregorad323a82010-01-27 03:51:04 +00001743// Per 13.3.3.2p3, compare the given standard conversion sequences to
1744// determine if one is a proper subset of the other.
1745static ImplicitConversionSequence::CompareKind
1746compareStandardConversionSubsets(ASTContext &Context,
1747 const StandardConversionSequence& SCS1,
1748 const StandardConversionSequence& SCS2) {
1749 ImplicitConversionSequence::CompareKind Result
1750 = ImplicitConversionSequence::Indistinguishable;
1751
1752 if (SCS1.Second != SCS2.Second) {
1753 if (SCS1.Second == ICK_Identity)
1754 Result = ImplicitConversionSequence::Better;
1755 else if (SCS2.Second == ICK_Identity)
1756 Result = ImplicitConversionSequence::Worse;
1757 else
1758 return ImplicitConversionSequence::Indistinguishable;
1759 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
1760 return ImplicitConversionSequence::Indistinguishable;
1761
1762 if (SCS1.Third == SCS2.Third) {
1763 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
1764 : ImplicitConversionSequence::Indistinguishable;
1765 }
1766
1767 if (SCS1.Third == ICK_Identity)
1768 return Result == ImplicitConversionSequence::Worse
1769 ? ImplicitConversionSequence::Indistinguishable
1770 : ImplicitConversionSequence::Better;
1771
1772 if (SCS2.Third == ICK_Identity)
1773 return Result == ImplicitConversionSequence::Better
1774 ? ImplicitConversionSequence::Indistinguishable
1775 : ImplicitConversionSequence::Worse;
1776
1777 return ImplicitConversionSequence::Indistinguishable;
1778}
1779
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001780/// CompareStandardConversionSequences - Compare two standard
1781/// conversion sequences to determine whether one is better than the
1782/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001783ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001784Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1785 const StandardConversionSequence& SCS2)
1786{
1787 // Standard conversion sequence S1 is a better conversion sequence
1788 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1789
1790 // -- S1 is a proper subsequence of S2 (comparing the conversion
1791 // sequences in the canonical form defined by 13.3.3.1.1,
1792 // excluding any Lvalue Transformation; the identity conversion
1793 // sequence is considered to be a subsequence of any
1794 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00001795 if (ImplicitConversionSequence::CompareKind CK
1796 = compareStandardConversionSubsets(Context, SCS1, SCS2))
1797 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001798
1799 // -- the rank of S1 is better than the rank of S2 (by the rules
1800 // defined below), or, if not that,
1801 ImplicitConversionRank Rank1 = SCS1.getRank();
1802 ImplicitConversionRank Rank2 = SCS2.getRank();
1803 if (Rank1 < Rank2)
1804 return ImplicitConversionSequence::Better;
1805 else if (Rank2 < Rank1)
1806 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001807
Douglas Gregor57373262008-10-22 14:17:15 +00001808 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1809 // are indistinguishable unless one of the following rules
1810 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00001811
Douglas Gregor57373262008-10-22 14:17:15 +00001812 // A conversion that is not a conversion of a pointer, or
1813 // pointer to member, to bool is better than another conversion
1814 // that is such a conversion.
1815 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1816 return SCS2.isPointerConversionToBool()
1817 ? ImplicitConversionSequence::Better
1818 : ImplicitConversionSequence::Worse;
1819
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001820 // C++ [over.ics.rank]p4b2:
1821 //
1822 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001823 // conversion of B* to A* is better than conversion of B* to
1824 // void*, and conversion of A* to void* is better than conversion
1825 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00001826 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001827 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001828 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001829 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001830 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1831 // Exactly one of the conversion sequences is a conversion to
1832 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001833 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1834 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001835 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1836 // Neither conversion sequence converts to a void pointer; compare
1837 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001838 if (ImplicitConversionSequence::CompareKind DerivedCK
1839 = CompareDerivedToBaseConversions(SCS1, SCS2))
1840 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001841 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1842 // Both conversion sequences are conversions to void
1843 // pointers. Compare the source types to determine if there's an
1844 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00001845 QualType FromType1 = SCS1.getFromType();
1846 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001847
1848 // Adjust the types we're converting from via the array-to-pointer
1849 // conversion, if we need to.
1850 if (SCS1.First == ICK_Array_To_Pointer)
1851 FromType1 = Context.getArrayDecayedType(FromType1);
1852 if (SCS2.First == ICK_Array_To_Pointer)
1853 FromType2 = Context.getArrayDecayedType(FromType2);
1854
Douglas Gregor01919692009-12-13 21:37:05 +00001855 QualType FromPointee1
1856 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1857 QualType FromPointee2
1858 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001859
Douglas Gregor01919692009-12-13 21:37:05 +00001860 if (IsDerivedFrom(FromPointee2, FromPointee1))
1861 return ImplicitConversionSequence::Better;
1862 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1863 return ImplicitConversionSequence::Worse;
1864
1865 // Objective-C++: If one interface is more specific than the
1866 // other, it is the better one.
1867 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1868 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1869 if (FromIface1 && FromIface1) {
1870 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1871 return ImplicitConversionSequence::Better;
1872 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1873 return ImplicitConversionSequence::Worse;
1874 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001875 }
Douglas Gregor57373262008-10-22 14:17:15 +00001876
1877 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1878 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00001879 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001880 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001881 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001882
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001883 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001884 // C++0x [over.ics.rank]p3b4:
1885 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1886 // implicit object parameter of a non-static member function declared
1887 // without a ref-qualifier, and S1 binds an rvalue reference to an
1888 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00001889 // FIXME: We don't know if we're dealing with the implicit object parameter,
1890 // or if the member function in this case has a ref qualifier.
1891 // (Of course, we don't have ref qualifiers yet.)
1892 if (SCS1.RRefBinding != SCS2.RRefBinding)
1893 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1894 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001895
1896 // C++ [over.ics.rank]p3b4:
1897 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1898 // which the references refer are the same type except for
1899 // top-level cv-qualifiers, and the type to which the reference
1900 // initialized by S2 refers is more cv-qualified than the type
1901 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00001902 QualType T1 = SCS1.getToType(2);
1903 QualType T2 = SCS2.getToType(2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001904 T1 = Context.getCanonicalType(T1);
1905 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00001906 Qualifiers T1Quals, T2Quals;
1907 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1908 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1909 if (UnqualT1 == UnqualT2) {
1910 // If the type is an array type, promote the element qualifiers to the type
1911 // for comparison.
1912 if (isa<ArrayType>(T1) && T1Quals)
1913 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1914 if (isa<ArrayType>(T2) && T2Quals)
1915 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001916 if (T2.isMoreQualifiedThan(T1))
1917 return ImplicitConversionSequence::Better;
1918 else if (T1.isMoreQualifiedThan(T2))
1919 return ImplicitConversionSequence::Worse;
1920 }
1921 }
Douglas Gregor57373262008-10-22 14:17:15 +00001922
1923 return ImplicitConversionSequence::Indistinguishable;
1924}
1925
1926/// CompareQualificationConversions - Compares two standard conversion
1927/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00001928/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1929ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00001930Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00001931 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00001932 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001933 // -- S1 and S2 differ only in their qualification conversion and
1934 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1935 // cv-qualification signature of type T1 is a proper subset of
1936 // the cv-qualification signature of type T2, and S1 is not the
1937 // deprecated string literal array-to-pointer conversion (4.2).
1938 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1939 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1940 return ImplicitConversionSequence::Indistinguishable;
1941
1942 // FIXME: the example in the standard doesn't use a qualification
1943 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00001944 QualType T1 = SCS1.getToType(2);
1945 QualType T2 = SCS2.getToType(2);
Douglas Gregor57373262008-10-22 14:17:15 +00001946 T1 = Context.getCanonicalType(T1);
1947 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00001948 Qualifiers T1Quals, T2Quals;
1949 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1950 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00001951
1952 // If the types are the same, we won't learn anything by unwrapped
1953 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00001954 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00001955 return ImplicitConversionSequence::Indistinguishable;
1956
Chandler Carruth28e318c2009-12-29 07:16:59 +00001957 // If the type is an array type, promote the element qualifiers to the type
1958 // for comparison.
1959 if (isa<ArrayType>(T1) && T1Quals)
1960 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1961 if (isa<ArrayType>(T2) && T2Quals)
1962 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1963
Mike Stump1eb44332009-09-09 15:08:12 +00001964 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00001965 = ImplicitConversionSequence::Indistinguishable;
1966 while (UnwrapSimilarPointerTypes(T1, T2)) {
1967 // Within each iteration of the loop, we check the qualifiers to
1968 // determine if this still looks like a qualification
1969 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001970 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001971 // until there are no more pointers or pointers-to-members left
1972 // to unwrap. This essentially mimics what
1973 // IsQualificationConversion does, but here we're checking for a
1974 // strict subset of qualifiers.
1975 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1976 // The qualifiers are the same, so this doesn't tell us anything
1977 // about how the sequences rank.
1978 ;
1979 else if (T2.isMoreQualifiedThan(T1)) {
1980 // T1 has fewer qualifiers, so it could be the better sequence.
1981 if (Result == ImplicitConversionSequence::Worse)
1982 // Neither has qualifiers that are a subset of the other's
1983 // qualifiers.
1984 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Douglas Gregor57373262008-10-22 14:17:15 +00001986 Result = ImplicitConversionSequence::Better;
1987 } else if (T1.isMoreQualifiedThan(T2)) {
1988 // T2 has fewer qualifiers, so it could be the better sequence.
1989 if (Result == ImplicitConversionSequence::Better)
1990 // Neither has qualifiers that are a subset of the other's
1991 // qualifiers.
1992 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Douglas Gregor57373262008-10-22 14:17:15 +00001994 Result = ImplicitConversionSequence::Worse;
1995 } else {
1996 // Qualifiers are disjoint.
1997 return ImplicitConversionSequence::Indistinguishable;
1998 }
1999
2000 // If the types after this point are equivalent, we're done.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002001 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002002 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002003 }
2004
Douglas Gregor57373262008-10-22 14:17:15 +00002005 // Check that the winning standard conversion sequence isn't using
2006 // the deprecated string literal array to pointer conversion.
2007 switch (Result) {
2008 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002009 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002010 Result = ImplicitConversionSequence::Indistinguishable;
2011 break;
2012
2013 case ImplicitConversionSequence::Indistinguishable:
2014 break;
2015
2016 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002017 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002018 Result = ImplicitConversionSequence::Indistinguishable;
2019 break;
2020 }
2021
2022 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002023}
2024
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002025/// CompareDerivedToBaseConversions - Compares two standard conversion
2026/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002027/// various kinds of derived-to-base conversions (C++
2028/// [over.ics.rank]p4b3). As part of these checks, we also look at
2029/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002030ImplicitConversionSequence::CompareKind
2031Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2032 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002033 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002034 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002035 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002036 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002037
2038 // Adjust the types we're converting from via the array-to-pointer
2039 // conversion, if we need to.
2040 if (SCS1.First == ICK_Array_To_Pointer)
2041 FromType1 = Context.getArrayDecayedType(FromType1);
2042 if (SCS2.First == ICK_Array_To_Pointer)
2043 FromType2 = Context.getArrayDecayedType(FromType2);
2044
2045 // Canonicalize all of the types.
2046 FromType1 = Context.getCanonicalType(FromType1);
2047 ToType1 = Context.getCanonicalType(ToType1);
2048 FromType2 = Context.getCanonicalType(FromType2);
2049 ToType2 = Context.getCanonicalType(ToType2);
2050
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002051 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002052 //
2053 // If class B is derived directly or indirectly from class A and
2054 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002055 //
2056 // For Objective-C, we let A, B, and C also be Objective-C
2057 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002058
2059 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002060 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002061 SCS2.Second == ICK_Pointer_Conversion &&
2062 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2063 FromType1->isPointerType() && FromType2->isPointerType() &&
2064 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002065 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002066 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002067 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002068 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002069 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002070 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002071 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002072 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002073
John McCall183700f2009-09-21 23:43:11 +00002074 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2075 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2076 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2077 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002078
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002079 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002080 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2081 if (IsDerivedFrom(ToPointee1, ToPointee2))
2082 return ImplicitConversionSequence::Better;
2083 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2084 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002085
2086 if (ToIface1 && ToIface2) {
2087 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2088 return ImplicitConversionSequence::Better;
2089 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2090 return ImplicitConversionSequence::Worse;
2091 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002092 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002093
2094 // -- conversion of B* to A* is better than conversion of C* to A*,
2095 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2096 if (IsDerivedFrom(FromPointee2, FromPointee1))
2097 return ImplicitConversionSequence::Better;
2098 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2099 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002100
Douglas Gregorcb7de522008-11-26 23:31:11 +00002101 if (FromIface1 && FromIface2) {
2102 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2103 return ImplicitConversionSequence::Better;
2104 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2105 return ImplicitConversionSequence::Worse;
2106 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002107 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002108 }
2109
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002110 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002111 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2112 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2113 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2114 const MemberPointerType * FromMemPointer1 =
2115 FromType1->getAs<MemberPointerType>();
2116 const MemberPointerType * ToMemPointer1 =
2117 ToType1->getAs<MemberPointerType>();
2118 const MemberPointerType * FromMemPointer2 =
2119 FromType2->getAs<MemberPointerType>();
2120 const MemberPointerType * ToMemPointer2 =
2121 ToType2->getAs<MemberPointerType>();
2122 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2123 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2124 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2125 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2126 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2127 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2128 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2129 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002130 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002131 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2132 if (IsDerivedFrom(ToPointee1, ToPointee2))
2133 return ImplicitConversionSequence::Worse;
2134 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2135 return ImplicitConversionSequence::Better;
2136 }
2137 // conversion of B::* to C::* is better than conversion of A::* to C::*
2138 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2139 if (IsDerivedFrom(FromPointee1, FromPointee2))
2140 return ImplicitConversionSequence::Better;
2141 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2142 return ImplicitConversionSequence::Worse;
2143 }
2144 }
2145
Douglas Gregor9e239322010-02-25 19:01:05 +00002146 if ((SCS1.ReferenceBinding || SCS1.CopyConstructor) &&
2147 (SCS2.ReferenceBinding || SCS2.CopyConstructor) &&
Douglas Gregor225c41e2008-11-03 19:09:14 +00002148 SCS1.Second == ICK_Derived_To_Base) {
2149 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00002150 // -- binding of an expression of type C to a reference of type
2151 // B& is better than binding an expression of type C to a
2152 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002153 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2154 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002155 if (IsDerivedFrom(ToType1, ToType2))
2156 return ImplicitConversionSequence::Better;
2157 else if (IsDerivedFrom(ToType2, ToType1))
2158 return ImplicitConversionSequence::Worse;
2159 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002160
Douglas Gregor225c41e2008-11-03 19:09:14 +00002161 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00002162 // -- binding of an expression of type B to a reference of type
2163 // A& is better than binding an expression of type C to a
2164 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002165 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2166 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002167 if (IsDerivedFrom(FromType2, FromType1))
2168 return ImplicitConversionSequence::Better;
2169 else if (IsDerivedFrom(FromType1, FromType2))
2170 return ImplicitConversionSequence::Worse;
2171 }
2172 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002173
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002174 return ImplicitConversionSequence::Indistinguishable;
2175}
2176
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002177/// TryCopyInitialization - Try to copy-initialize a value of type
2178/// ToType from the expression From. Return the implicit conversion
2179/// sequence required to pass this argument, which may be a bad
2180/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00002181/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redle2b68332009-04-12 17:16:29 +00002182/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2183/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00002184ImplicitConversionSequence
2185Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002186 bool SuppressUserConversions, bool ForceRValue,
2187 bool InOverloadResolution) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00002188 if (ToType->isReferenceType()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002189 ImplicitConversionSequence ICS;
John McCallb1bdc622010-02-25 01:37:24 +00002190 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00002191 CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00002192 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002193 SuppressUserConversions,
2194 /*AllowExplicit=*/false,
2195 ForceRValue,
2196 &ICS);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002197 return ICS;
2198 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002199 return TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002200 SuppressUserConversions,
2201 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002202 ForceRValue,
2203 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002204 }
2205}
2206
Douglas Gregor96176b32008-11-18 23:14:02 +00002207/// TryObjectArgumentInitialization - Try to initialize the object
2208/// parameter of the given member function (@c Method) from the
2209/// expression @p From.
2210ImplicitConversionSequence
John McCall651f3ee2010-01-14 03:28:57 +00002211Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall701c89e2009-12-03 04:06:58 +00002212 CXXMethodDecl *Method,
2213 CXXRecordDecl *ActingContext) {
2214 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002215 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2216 // const volatile object.
2217 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2218 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2219 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00002220
2221 // Set up the conversion sequence as a "bad" conversion, to allow us
2222 // to exit early.
2223 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00002224
2225 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00002226 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002227 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00002228 FromType = PT->getPointeeType();
2229
2230 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002231
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002232 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00002233 // where X is the class of which the function is a member
2234 // (C++ [over.match.funcs]p4). However, when finding an implicit
2235 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00002236 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00002237 // (C++ [over.match.funcs]p5). We perform a simplified version of
2238 // reference binding here, that allows class rvalues to bind to
2239 // non-constant references.
2240
2241 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2242 // with the implicit object parameter (C++ [over.match.funcs]p5).
2243 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002244 if (ImplicitParamType.getCVRQualifiers()
2245 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00002246 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00002247 ICS.setBad(BadConversionSequence::bad_qualifiers,
2248 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002249 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002250 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002251
2252 // Check that we have either the same type or a derived type. It
2253 // affects the conversion rank.
2254 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00002255 ImplicitConversionKind SecondKind;
2256 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2257 SecondKind = ICK_Identity;
2258 } else if (IsDerivedFrom(FromType, ClassType))
2259 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00002260 else {
John McCallb1bdc622010-02-25 01:37:24 +00002261 ICS.setBad(BadConversionSequence::unrelated_class,
2262 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002263 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002264 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002265
2266 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00002267 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00002268 ICS.Standard.setAsIdentityConversion();
2269 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00002270 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00002271 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002272 ICS.Standard.ReferenceBinding = true;
2273 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00002274 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002275 return ICS;
2276}
2277
2278/// PerformObjectArgumentInitialization - Perform initialization of
2279/// the implicit object parameter for the given Method with the given
2280/// expression.
2281bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00002282Sema::PerformObjectArgumentInitialization(Expr *&From,
2283 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002284 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002285 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002286 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00002287 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00002288 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002289
Ted Kremenek6217b802009-07-29 21:53:49 +00002290 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002291 FromRecordType = PT->getPointeeType();
2292 DestType = Method->getThisType(Context);
2293 } else {
2294 FromRecordType = From->getType();
2295 DestType = ImplicitParamRecordType;
2296 }
2297
John McCall701c89e2009-12-03 04:06:58 +00002298 // Note that we always use the true parent context when performing
2299 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002300 ImplicitConversionSequence ICS
John McCall701c89e2009-12-03 04:06:58 +00002301 = TryObjectArgumentInitialization(From->getType(), Method,
2302 Method->getParent());
John McCall1d318332010-01-12 00:44:57 +00002303 if (ICS.isBad())
Douglas Gregor96176b32008-11-18 23:14:02 +00002304 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002305 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00002306 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002307
Douglas Gregor5fccd362010-03-03 23:55:11 +00002308 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall6bb80172010-03-30 21:47:33 +00002309 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor96176b32008-11-18 23:14:02 +00002310
Douglas Gregor5fccd362010-03-03 23:55:11 +00002311 if (!Context.hasSameType(From->getType(), DestType))
2312 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2313 /*isLvalue=*/!From->getType()->getAs<PointerType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00002314 return false;
2315}
2316
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002317/// TryContextuallyConvertToBool - Attempt to contextually convert the
2318/// expression From to bool (C++0x [conv]p3).
2319ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump1eb44332009-09-09 15:08:12 +00002320 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002321 // FIXME: Are these flags correct?
2322 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00002323 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00002324 /*ForceRValue=*/false,
2325 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002326}
2327
2328/// PerformContextuallyConvertToBool - Perform a contextual conversion
2329/// of the expression From to bool (C++0x [conv]p3).
2330bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2331 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall1d318332010-01-12 00:44:57 +00002332 if (!ICS.isBad())
2333 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002334
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002335 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002336 return Diag(From->getSourceRange().getBegin(),
2337 diag::err_typecheck_bool_condition)
2338 << From->getType() << From->getSourceRange();
2339 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002340}
2341
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002342/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00002343/// candidate functions, using the given function call arguments. If
2344/// @p SuppressUserConversions, then don't allow user-defined
2345/// conversions via constructors or conversion operators.
Sebastian Redle2b68332009-04-12 17:16:29 +00002346/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2347/// hacky way to implement the overloading rules for elidable copy
2348/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002349///
2350/// \para PartialOverloading true if we are performing "partial" overloading
2351/// based on an incomplete set of function arguments. This feature is used by
2352/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00002353void
2354Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002355 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002356 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002357 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00002358 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002359 bool ForceRValue,
2360 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00002361 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002362 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002363 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00002364 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00002365 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00002366
Douglas Gregor88a35142008-12-22 05:46:06 +00002367 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002368 if (!isa<CXXConstructorDecl>(Method)) {
2369 // If we get here, it's because we're calling a member function
2370 // that is named without a member access expression (e.g.,
2371 // "this->f") that was either written explicitly or created
2372 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00002373 // function, e.g., X::f(). We use an empty type for the implied
2374 // object argument (C++ [over.call.func]p3), and the acting context
2375 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00002376 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00002377 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002378 SuppressUserConversions, ForceRValue);
2379 return;
2380 }
2381 // We treat a constructor like a non-member function, since its object
2382 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00002383 }
2384
Douglas Gregorfd476482009-11-13 23:59:09 +00002385 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00002386 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00002387
Douglas Gregor7edfb692009-11-23 12:27:39 +00002388 // Overload resolution is always an unevaluated context.
2389 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2390
Douglas Gregor66724ea2009-11-14 01:20:54 +00002391 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2392 // C++ [class.copy]p3:
2393 // A member function template is never instantiated to perform the copy
2394 // of a class object to an object of its class type.
2395 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2396 if (NumArgs == 1 &&
2397 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor12116062010-02-21 18:30:38 +00002398 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
2399 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00002400 return;
2401 }
2402
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002403 // Add this candidate
2404 CandidateSet.push_back(OverloadCandidate());
2405 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00002406 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002407 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00002408 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002409 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002410 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002411
2412 unsigned NumArgsInProto = Proto->getNumArgs();
2413
2414 // (C++ 13.3.2p2): A candidate function having fewer than m
2415 // parameters is viable only if it has an ellipsis in its parameter
2416 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00002417 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2418 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002419 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002420 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002421 return;
2422 }
2423
2424 // (C++ 13.3.2p2): A candidate function having more than m parameters
2425 // is viable only if the (m+1)st parameter has a default argument
2426 // (8.3.6). For the purposes of overload resolution, the
2427 // parameter list is truncated on the right, so that there are
2428 // exactly m parameters.
2429 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002430 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002431 // Not enough arguments.
2432 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002433 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002434 return;
2435 }
2436
2437 // Determine the implicit conversion sequences for each of the
2438 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002439 Candidate.Conversions.resize(NumArgs);
2440 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2441 if (ArgIdx < NumArgsInProto) {
2442 // (C++ 13.3.2p3): for F to be a viable function, there shall
2443 // exist for each argument an implicit conversion sequence
2444 // (13.3.3.1) that converts that argument to the corresponding
2445 // parameter of F.
2446 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002447 Candidate.Conversions[ArgIdx]
2448 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002449 SuppressUserConversions, ForceRValue,
2450 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00002451 if (Candidate.Conversions[ArgIdx].isBad()) {
2452 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002453 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00002454 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00002455 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002456 } else {
2457 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2458 // argument for which there is no corresponding parameter is
2459 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00002460 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002461 }
2462 }
2463}
2464
Douglas Gregor063daf62009-03-13 18:40:31 +00002465/// \brief Add all of the function declarations in the given function set to
2466/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00002467void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00002468 Expr **Args, unsigned NumArgs,
2469 OverloadCandidateSet& CandidateSet,
2470 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00002471 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00002472 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
2473 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002474 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00002475 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00002476 cast<CXXMethodDecl>(FD)->getParent(),
2477 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00002478 CandidateSet, SuppressUserConversions);
2479 else
John McCall9aa472c2010-03-19 07:35:19 +00002480 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00002481 SuppressUserConversions);
2482 } else {
John McCall9aa472c2010-03-19 07:35:19 +00002483 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00002484 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2485 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00002486 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00002487 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00002488 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00002489 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00002490 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00002491 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00002492 else
John McCall9aa472c2010-03-19 07:35:19 +00002493 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00002494 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00002495 Args, NumArgs, CandidateSet,
2496 SuppressUserConversions);
2497 }
Douglas Gregor364e0212009-06-27 21:05:07 +00002498 }
Douglas Gregor063daf62009-03-13 18:40:31 +00002499}
2500
John McCall314be4e2009-11-17 07:50:12 +00002501/// AddMethodCandidate - Adds a named decl (which is some kind of
2502/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00002503void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00002504 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00002505 Expr **Args, unsigned NumArgs,
2506 OverloadCandidateSet& CandidateSet,
2507 bool SuppressUserConversions, bool ForceRValue) {
John McCall9aa472c2010-03-19 07:35:19 +00002508 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00002509 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00002510
2511 if (isa<UsingShadowDecl>(Decl))
2512 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2513
2514 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2515 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2516 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00002517 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
2518 /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00002519 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00002520 CandidateSet,
2521 SuppressUserConversions,
2522 ForceRValue);
2523 } else {
John McCall9aa472c2010-03-19 07:35:19 +00002524 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00002525 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00002526 CandidateSet, SuppressUserConversions, ForceRValue);
2527 }
2528}
2529
Douglas Gregor96176b32008-11-18 23:14:02 +00002530/// AddMethodCandidate - Adds the given C++ member function to the set
2531/// of candidate functions, using the given function call arguments
2532/// and the object argument (@c Object). For example, in a call
2533/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2534/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2535/// allow user-defined conversions via constructors or conversion
Sebastian Redle2b68332009-04-12 17:16:29 +00002536/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2537/// a slightly hacky way to implement the overloading rules for elidable copy
2538/// initialization in C++0x (C++0x 12.8p15).
Mike Stump1eb44332009-09-09 15:08:12 +00002539void
John McCall9aa472c2010-03-19 07:35:19 +00002540Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002541 CXXRecordDecl *ActingContext, QualType ObjectType,
2542 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00002543 OverloadCandidateSet& CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00002544 bool SuppressUserConversions, bool ForceRValue) {
2545 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002546 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00002547 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002548 assert(!isa<CXXConstructorDecl>(Method) &&
2549 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00002550
Douglas Gregor3f396022009-09-28 04:47:19 +00002551 if (!CandidateSet.isNewCandidate(Method))
2552 return;
2553
Douglas Gregor7edfb692009-11-23 12:27:39 +00002554 // Overload resolution is always an unevaluated context.
2555 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2556
Douglas Gregor96176b32008-11-18 23:14:02 +00002557 // Add this candidate
2558 CandidateSet.push_back(OverloadCandidate());
2559 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00002560 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00002561 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002562 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002563 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002564
2565 unsigned NumArgsInProto = Proto->getNumArgs();
2566
2567 // (C++ 13.3.2p2): A candidate function having fewer than m
2568 // parameters is viable only if it has an ellipsis in its parameter
2569 // list (8.3.5).
2570 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2571 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002572 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00002573 return;
2574 }
2575
2576 // (C++ 13.3.2p2): A candidate function having more than m parameters
2577 // is viable only if the (m+1)st parameter has a default argument
2578 // (8.3.6). For the purposes of overload resolution, the
2579 // parameter list is truncated on the right, so that there are
2580 // exactly m parameters.
2581 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2582 if (NumArgs < MinRequiredArgs) {
2583 // Not enough arguments.
2584 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002585 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00002586 return;
2587 }
2588
2589 Candidate.Viable = true;
2590 Candidate.Conversions.resize(NumArgs + 1);
2591
John McCall701c89e2009-12-03 04:06:58 +00002592 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00002593 // The implicit object argument is ignored.
2594 Candidate.IgnoreObjectArgument = true;
2595 else {
2596 // Determine the implicit conversion sequence for the object
2597 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00002598 Candidate.Conversions[0]
2599 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00002600 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002601 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002602 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00002603 return;
2604 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002605 }
2606
2607 // Determine the implicit conversion sequences for each of the
2608 // arguments.
2609 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2610 if (ArgIdx < NumArgsInProto) {
2611 // (C++ 13.3.2p3): for F to be a viable function, there shall
2612 // exist for each argument an implicit conversion sequence
2613 // (13.3.3.1) that converts that argument to the corresponding
2614 // parameter of F.
2615 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002616 Candidate.Conversions[ArgIdx + 1]
2617 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002618 SuppressUserConversions, ForceRValue,
Anders Carlsson08972922009-08-28 15:33:32 +00002619 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00002620 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002621 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002622 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00002623 break;
2624 }
2625 } else {
2626 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2627 // argument for which there is no corresponding parameter is
2628 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00002629 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00002630 }
2631 }
2632}
2633
Douglas Gregor6b906862009-08-21 00:16:32 +00002634/// \brief Add a C++ member function template as a candidate to the candidate
2635/// set, using template argument deduction to produce an appropriate member
2636/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002637void
Douglas Gregor6b906862009-08-21 00:16:32 +00002638Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00002639 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00002640 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00002641 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00002642 QualType ObjectType,
2643 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002644 OverloadCandidateSet& CandidateSet,
2645 bool SuppressUserConversions,
2646 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002647 if (!CandidateSet.isNewCandidate(MethodTmpl))
2648 return;
2649
Douglas Gregor6b906862009-08-21 00:16:32 +00002650 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002651 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00002652 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002653 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00002654 // candidate functions in the usual way.113) A given name can refer to one
2655 // or more function templates and also to a set of overloaded non-template
2656 // functions. In such a case, the candidate functions generated from each
2657 // function template are combined with the set of non-template candidate
2658 // functions.
John McCall5769d612010-02-08 23:07:23 +00002659 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00002660 FunctionDecl *Specialization = 0;
2661 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00002662 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002663 Args, NumArgs, Specialization, Info)) {
2664 // FIXME: Record what happened with template argument deduction, so
2665 // that we can give the user a beautiful diagnostic.
2666 (void)Result;
2667 return;
2668 }
Mike Stump1eb44332009-09-09 15:08:12 +00002669
Douglas Gregor6b906862009-08-21 00:16:32 +00002670 // Add the function template specialization produced by template argument
2671 // deduction as a candidate.
2672 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00002673 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00002674 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00002675 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002676 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002677 CandidateSet, SuppressUserConversions, ForceRValue);
2678}
2679
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002680/// \brief Add a C++ function template specialization as a candidate
2681/// in the candidate set, using template argument deduction to produce
2682/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002683void
Douglas Gregore53060f2009-06-25 22:08:12 +00002684Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00002685 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00002686 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002687 Expr **Args, unsigned NumArgs,
2688 OverloadCandidateSet& CandidateSet,
2689 bool SuppressUserConversions,
2690 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002691 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2692 return;
2693
Douglas Gregore53060f2009-06-25 22:08:12 +00002694 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002695 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00002696 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002697 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00002698 // candidate functions in the usual way.113) A given name can refer to one
2699 // or more function templates and also to a set of overloaded non-template
2700 // functions. In such a case, the candidate functions generated from each
2701 // function template are combined with the set of non-template candidate
2702 // functions.
John McCall5769d612010-02-08 23:07:23 +00002703 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00002704 FunctionDecl *Specialization = 0;
2705 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00002706 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002707 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00002708 CandidateSet.push_back(OverloadCandidate());
2709 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00002710 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00002711 Candidate.Function = FunctionTemplate->getTemplatedDecl();
2712 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002713 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00002714 Candidate.IsSurrogate = false;
2715 Candidate.IgnoreObjectArgument = false;
John McCall342fec42010-02-01 18:53:26 +00002716
2717 // TODO: record more information about failed template arguments
2718 Candidate.DeductionFailure.Result = Result;
2719 Candidate.DeductionFailure.TemplateParameter = Info.Param.getOpaqueValue();
Douglas Gregore53060f2009-06-25 22:08:12 +00002720 return;
2721 }
Mike Stump1eb44332009-09-09 15:08:12 +00002722
Douglas Gregore53060f2009-06-25 22:08:12 +00002723 // Add the function template specialization produced by template argument
2724 // deduction as a candidate.
2725 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00002726 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregore53060f2009-06-25 22:08:12 +00002727 SuppressUserConversions, ForceRValue);
2728}
Mike Stump1eb44332009-09-09 15:08:12 +00002729
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002730/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00002731/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002732/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00002733/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002734/// (which may or may not be the same type as the type that the
2735/// conversion function produces).
2736void
2737Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00002738 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00002739 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002740 Expr *From, QualType ToType,
2741 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002742 assert(!Conversion->getDescribedFunctionTemplate() &&
2743 "Conversion function templates use AddTemplateConversionCandidate");
2744
Douglas Gregor3f396022009-09-28 04:47:19 +00002745 if (!CandidateSet.isNewCandidate(Conversion))
2746 return;
2747
Douglas Gregor7edfb692009-11-23 12:27:39 +00002748 // Overload resolution is always an unevaluated context.
2749 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2750
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002751 // Add this candidate
2752 CandidateSet.push_back(OverloadCandidate());
2753 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00002754 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002755 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002756 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002757 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002758 Candidate.FinalConversion.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00002759 Candidate.FinalConversion.setFromType(Conversion->getConversionType());
Douglas Gregorad323a82010-01-27 03:51:04 +00002760 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002761
Douglas Gregor96176b32008-11-18 23:14:02 +00002762 // Determine the implicit conversion sequence for the implicit
2763 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002764 Candidate.Viable = true;
2765 Candidate.Conversions.resize(1);
John McCall701c89e2009-12-03 04:06:58 +00002766 Candidate.Conversions[0]
2767 = TryObjectArgumentInitialization(From->getType(), Conversion,
2768 ActingContext);
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002769 // Conversion functions to a different type in the base class is visible in
2770 // the derived class. So, a derived to base conversion should not participate
2771 // in overload resolution.
2772 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2773 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall1d318332010-01-12 00:44:57 +00002774 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002775 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002776 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002777 return;
2778 }
Fariborz Jahanian3759a032009-10-19 19:18:20 +00002779
2780 // We won't go through a user-define type conversion function to convert a
2781 // derived to base as such conversions are given Conversion Rank. They only
2782 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2783 QualType FromCanon
2784 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2785 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2786 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2787 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00002788 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00002789 return;
2790 }
2791
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002792
2793 // To determine what the conversion from the result of calling the
2794 // conversion function to the type we're eventually trying to
2795 // convert to (ToType), we need to synthesize a call to the
2796 // conversion function and attempt copy initialization from it. This
2797 // makes sure that we get the right semantics with respect to
2798 // lvalues/rvalues and the type. Fortunately, we can allocate this
2799 // call on the stack and we don't need its arguments to be
2800 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00002801 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002802 From->getLocStart());
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002803 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman73c39ab2009-10-20 08:27:19 +00002804 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002805 &ConversionRef, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002806
2807 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00002808 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2809 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00002810 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002811 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002812 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00002813 ImplicitConversionSequence ICS =
2814 TryCopyInitialization(&Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002815 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002816 /*ForceRValue=*/false,
2817 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002818
John McCall1d318332010-01-12 00:44:57 +00002819 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002820 case ImplicitConversionSequence::StandardConversion:
2821 Candidate.FinalConversion = ICS.Standard;
2822 break;
2823
2824 case ImplicitConversionSequence::BadConversion:
2825 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00002826 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002827 break;
2828
2829 default:
Mike Stump1eb44332009-09-09 15:08:12 +00002830 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002831 "Can only end up with a standard conversion sequence or failure");
2832 }
2833}
2834
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002835/// \brief Adds a conversion function template specialization
2836/// candidate to the overload set, using template argument deduction
2837/// to deduce the template arguments of the conversion function
2838/// template from the type that we are converting to (C++
2839/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00002840void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002841Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00002842 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00002843 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002844 Expr *From, QualType ToType,
2845 OverloadCandidateSet &CandidateSet) {
2846 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2847 "Only conversion function templates permitted here");
2848
Douglas Gregor3f396022009-09-28 04:47:19 +00002849 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2850 return;
2851
John McCall5769d612010-02-08 23:07:23 +00002852 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002853 CXXConversionDecl *Specialization = 0;
2854 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00002855 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002856 Specialization, Info)) {
2857 // FIXME: Record what happened with template argument deduction, so
2858 // that we can give the user a beautiful diagnostic.
2859 (void)Result;
2860 return;
2861 }
Mike Stump1eb44332009-09-09 15:08:12 +00002862
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002863 // Add the conversion function template specialization produced by
2864 // template argument deduction as a candidate.
2865 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00002866 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00002867 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002868}
2869
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002870/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2871/// converts the given @c Object to a function pointer via the
2872/// conversion function @c Conversion, and then attempts to call it
2873/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2874/// the type of function that we'll eventually be calling.
2875void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00002876 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00002877 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00002878 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00002879 QualType ObjectType,
2880 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002881 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002882 if (!CandidateSet.isNewCandidate(Conversion))
2883 return;
2884
Douglas Gregor7edfb692009-11-23 12:27:39 +00002885 // Overload resolution is always an unevaluated context.
2886 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2887
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002888 CandidateSet.push_back(OverloadCandidate());
2889 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00002890 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002891 Candidate.Function = 0;
2892 Candidate.Surrogate = Conversion;
2893 Candidate.Viable = true;
2894 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002895 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002896 Candidate.Conversions.resize(NumArgs + 1);
2897
2898 // Determine the implicit conversion sequence for the implicit
2899 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00002900 ImplicitConversionSequence ObjectInit
John McCall701c89e2009-12-03 04:06:58 +00002901 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00002902 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002903 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002904 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00002905 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002906 return;
2907 }
2908
2909 // The first conversion is actually a user-defined conversion whose
2910 // first conversion is ObjectInit's standard conversion (which is
2911 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00002912 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002913 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002914 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002915 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00002916 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002917 = Candidate.Conversions[0].UserDefined.Before;
2918 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2919
Mike Stump1eb44332009-09-09 15:08:12 +00002920 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002921 unsigned NumArgsInProto = Proto->getNumArgs();
2922
2923 // (C++ 13.3.2p2): A candidate function having fewer than m
2924 // parameters is viable only if it has an ellipsis in its parameter
2925 // list (8.3.5).
2926 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2927 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002928 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002929 return;
2930 }
2931
2932 // Function types don't have any default arguments, so just check if
2933 // we have enough arguments.
2934 if (NumArgs < NumArgsInProto) {
2935 // Not enough arguments.
2936 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002937 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002938 return;
2939 }
2940
2941 // Determine the implicit conversion sequences for each of the
2942 // arguments.
2943 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2944 if (ArgIdx < NumArgsInProto) {
2945 // (C++ 13.3.2p3): for F to be a viable function, there shall
2946 // exist for each argument an implicit conversion sequence
2947 // (13.3.3.1) that converts that argument to the corresponding
2948 // parameter of F.
2949 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002950 Candidate.Conversions[ArgIdx + 1]
2951 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002952 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002953 /*ForceRValue=*/false,
2954 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00002955 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002956 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002957 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002958 break;
2959 }
2960 } else {
2961 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2962 // argument for which there is no corresponding parameter is
2963 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00002964 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002965 }
2966 }
2967}
2968
Mike Stump390b4cc2009-05-16 07:39:55 +00002969// FIXME: This will eventually be removed, once we've migrated all of the
2970// operator overloading logic over to the scheme used by binary operators, which
2971// works for template instantiation.
Douglas Gregor063daf62009-03-13 18:40:31 +00002972void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002973 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00002974 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002975 OverloadCandidateSet& CandidateSet,
2976 SourceRange OpRange) {
John McCall6e266892010-01-26 03:27:55 +00002977 UnresolvedSet<16> Fns;
Douglas Gregor063daf62009-03-13 18:40:31 +00002978
2979 QualType T1 = Args[0]->getType();
2980 QualType T2;
2981 if (NumArgs > 1)
2982 T2 = Args[1]->getType();
2983
2984 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002985 if (S)
John McCall6e266892010-01-26 03:27:55 +00002986 LookupOverloadedOperatorName(Op, S, T1, T2, Fns);
2987 AddFunctionCandidates(Fns, Args, NumArgs, CandidateSet, false);
2988 AddArgumentDependentLookupCandidates(OpName, false, Args, NumArgs, 0,
2989 CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00002990 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002991 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00002992}
2993
2994/// \brief Add overload candidates for overloaded operators that are
2995/// member functions.
2996///
2997/// Add the overloaded operator candidates that are member functions
2998/// for the operator Op that was used in an operator expression such
2999/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3000/// CandidateSet will store the added overload candidates. (C++
3001/// [over.match.oper]).
3002void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3003 SourceLocation OpLoc,
3004 Expr **Args, unsigned NumArgs,
3005 OverloadCandidateSet& CandidateSet,
3006 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003007 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3008
3009 // C++ [over.match.oper]p3:
3010 // For a unary operator @ with an operand of a type whose
3011 // cv-unqualified version is T1, and for a binary operator @ with
3012 // a left operand of a type whose cv-unqualified version is T1 and
3013 // a right operand of a type whose cv-unqualified version is T2,
3014 // three sets of candidate functions, designated member
3015 // candidates, non-member candidates and built-in candidates, are
3016 // constructed as follows:
3017 QualType T1 = Args[0]->getType();
3018 QualType T2;
3019 if (NumArgs > 1)
3020 T2 = Args[1]->getType();
3021
3022 // -- If T1 is a class type, the set of member candidates is the
3023 // result of the qualified lookup of T1::operator@
3024 // (13.3.1.1.1); otherwise, the set of member candidates is
3025 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00003026 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003027 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003028 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003029 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003030
John McCalla24dc2e2009-11-17 02:14:36 +00003031 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3032 LookupQualifiedName(Operators, T1Rec->getDecl());
3033 Operators.suppressDiagnostics();
3034
Mike Stump1eb44332009-09-09 15:08:12 +00003035 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003036 OperEnd = Operators.end();
3037 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00003038 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00003039 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00003040 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00003041 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00003042 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003043}
3044
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003045/// AddBuiltinCandidate - Add a candidate for a built-in
3046/// operator. ResultTy and ParamTys are the result and parameter types
3047/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003048/// arguments being passed to the candidate. IsAssignmentOperator
3049/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003050/// operator. NumContextualBoolArguments is the number of arguments
3051/// (at the beginning of the argument list) that will be contextually
3052/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00003053void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003054 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003055 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003056 bool IsAssignmentOperator,
3057 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00003058 // Overload resolution is always an unevaluated context.
3059 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3060
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003061 // Add this candidate
3062 CandidateSet.push_back(OverloadCandidate());
3063 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003064 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003065 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003066 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003067 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003068 Candidate.BuiltinTypes.ResultTy = ResultTy;
3069 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3070 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3071
3072 // Determine the implicit conversion sequences for each of the
3073 // arguments.
3074 Candidate.Viable = true;
3075 Candidate.Conversions.resize(NumArgs);
3076 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003077 // C++ [over.match.oper]p4:
3078 // For the built-in assignment operators, conversions of the
3079 // left operand are restricted as follows:
3080 // -- no temporaries are introduced to hold the left operand, and
3081 // -- no user-defined conversions are applied to the left
3082 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00003083 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003084 //
3085 // We block these conversions by turning off user-defined
3086 // conversions, since that is the only way that initialization of
3087 // a reference to a non-class type can occur from something that
3088 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003089 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00003090 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003091 "Contextual conversion to bool requires bool type");
3092 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3093 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003094 Candidate.Conversions[ArgIdx]
3095 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00003096 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003097 /*ForceRValue=*/false,
3098 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003099 }
John McCall1d318332010-01-12 00:44:57 +00003100 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003101 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003102 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003103 break;
3104 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003105 }
3106}
3107
3108/// BuiltinCandidateTypeSet - A set of types that will be used for the
3109/// candidate operator functions for built-in operators (C++
3110/// [over.built]). The types are separated into pointer types and
3111/// enumeration types.
3112class BuiltinCandidateTypeSet {
3113 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003114 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003115
3116 /// PointerTypes - The set of pointer types that will be used in the
3117 /// built-in candidates.
3118 TypeSet PointerTypes;
3119
Sebastian Redl78eb8742009-04-19 21:53:20 +00003120 /// MemberPointerTypes - The set of member pointer types that will be
3121 /// used in the built-in candidates.
3122 TypeSet MemberPointerTypes;
3123
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003124 /// EnumerationTypes - The set of enumeration types that will be
3125 /// used in the built-in candidates.
3126 TypeSet EnumerationTypes;
3127
Douglas Gregor5842ba92009-08-24 15:23:48 +00003128 /// Sema - The semantic analysis instance where we are building the
3129 /// candidate type set.
3130 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003131
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003132 /// Context - The AST context in which we will build the type sets.
3133 ASTContext &Context;
3134
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003135 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3136 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00003137 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003138
3139public:
3140 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003141 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003142
Mike Stump1eb44332009-09-09 15:08:12 +00003143 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00003144 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003145
Douglas Gregor573d9c32009-10-21 23:19:44 +00003146 void AddTypesConvertedFrom(QualType Ty,
3147 SourceLocation Loc,
3148 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003149 bool AllowExplicitConversions,
3150 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003151
3152 /// pointer_begin - First pointer type found;
3153 iterator pointer_begin() { return PointerTypes.begin(); }
3154
Sebastian Redl78eb8742009-04-19 21:53:20 +00003155 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003156 iterator pointer_end() { return PointerTypes.end(); }
3157
Sebastian Redl78eb8742009-04-19 21:53:20 +00003158 /// member_pointer_begin - First member pointer type found;
3159 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3160
3161 /// member_pointer_end - Past the last member pointer type found;
3162 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3163
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003164 /// enumeration_begin - First enumeration type found;
3165 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3166
Sebastian Redl78eb8742009-04-19 21:53:20 +00003167 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003168 iterator enumeration_end() { return EnumerationTypes.end(); }
3169};
3170
Sebastian Redl78eb8742009-04-19 21:53:20 +00003171/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003172/// the set of pointer types along with any more-qualified variants of
3173/// that type. For example, if @p Ty is "int const *", this routine
3174/// will add "int const *", "int const volatile *", "int const
3175/// restrict *", and "int const volatile restrict *" to the set of
3176/// pointer types. Returns true if the add of @p Ty itself succeeded,
3177/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003178///
3179/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003180bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00003181BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3182 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00003183
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003184 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003185 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003186 return false;
3187
John McCall0953e762009-09-24 19:53:00 +00003188 const PointerType *PointerTy = Ty->getAs<PointerType>();
3189 assert(PointerTy && "type was not a pointer type!");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003190
John McCall0953e762009-09-24 19:53:00 +00003191 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003192 // Don't add qualified variants of arrays. For one, they're not allowed
3193 // (the qualifier would sink to the element type), and for another, the
3194 // only overload situation where it matters is subscript or pointer +- int,
3195 // and those shouldn't have qualifier variants anyway.
3196 if (PointeeTy->isArrayType())
3197 return true;
John McCall0953e762009-09-24 19:53:00 +00003198 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00003199 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00003200 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003201 bool hasVolatile = VisibleQuals.hasVolatile();
3202 bool hasRestrict = VisibleQuals.hasRestrict();
3203
John McCall0953e762009-09-24 19:53:00 +00003204 // Iterate through all strict supersets of BaseCVR.
3205 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3206 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003207 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3208 // in the types.
3209 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3210 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00003211 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3212 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003213 }
3214
3215 return true;
3216}
3217
Sebastian Redl78eb8742009-04-19 21:53:20 +00003218/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3219/// to the set of pointer types along with any more-qualified variants of
3220/// that type. For example, if @p Ty is "int const *", this routine
3221/// will add "int const *", "int const volatile *", "int const
3222/// restrict *", and "int const volatile restrict *" to the set of
3223/// pointer types. Returns true if the add of @p Ty itself succeeded,
3224/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003225///
3226/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003227bool
3228BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3229 QualType Ty) {
3230 // Insert this type.
3231 if (!MemberPointerTypes.insert(Ty))
3232 return false;
3233
John McCall0953e762009-09-24 19:53:00 +00003234 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3235 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00003236
John McCall0953e762009-09-24 19:53:00 +00003237 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003238 // Don't add qualified variants of arrays. For one, they're not allowed
3239 // (the qualifier would sink to the element type), and for another, the
3240 // only overload situation where it matters is subscript or pointer +- int,
3241 // and those shouldn't have qualifier variants anyway.
3242 if (PointeeTy->isArrayType())
3243 return true;
John McCall0953e762009-09-24 19:53:00 +00003244 const Type *ClassTy = PointerTy->getClass();
3245
3246 // Iterate through all strict supersets of the pointee type's CVR
3247 // qualifiers.
3248 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3249 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3250 if ((CVR | BaseCVR) != CVR) continue;
3251
3252 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3253 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00003254 }
3255
3256 return true;
3257}
3258
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003259/// AddTypesConvertedFrom - Add each of the types to which the type @p
3260/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00003261/// primarily interested in pointer types and enumeration types. We also
3262/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003263/// AllowUserConversions is true if we should look at the conversion
3264/// functions of a class type, and AllowExplicitConversions if we
3265/// should also include the explicit conversion functions of a class
3266/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003267void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003268BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003269 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003270 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003271 bool AllowExplicitConversions,
3272 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003273 // Only deal with canonical types.
3274 Ty = Context.getCanonicalType(Ty);
3275
3276 // Look through reference types; they aren't part of the type of an
3277 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00003278 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003279 Ty = RefTy->getPointeeType();
3280
3281 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003282 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003283
Sebastian Redla65b5512009-11-05 16:36:20 +00003284 // If we're dealing with an array type, decay to the pointer.
3285 if (Ty->isArrayType())
3286 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3287
Ted Kremenek6217b802009-07-29 21:53:49 +00003288 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003289 QualType PointeeTy = PointerTy->getPointeeType();
3290
3291 // Insert our type, and its more-qualified variants, into the set
3292 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003293 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003294 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00003295 } else if (Ty->isMemberPointerType()) {
3296 // Member pointers are far easier, since the pointee can't be converted.
3297 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3298 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003299 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00003300 EnumerationTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003301 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003302 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003303 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003304 // No conversion functions in incomplete types.
3305 return;
3306 }
Mike Stump1eb44332009-09-09 15:08:12 +00003307
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003308 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00003309 const UnresolvedSetImpl *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00003310 = ClassDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003311 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003312 E = Conversions->end(); I != E; ++I) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003313
Mike Stump1eb44332009-09-09 15:08:12 +00003314 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003315 // about which builtin types we can convert to.
John McCallba135432009-11-21 08:51:07 +00003316 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003317 continue;
3318
John McCallba135432009-11-21 08:51:07 +00003319 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003320 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003321 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003322 VisibleQuals);
3323 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003324 }
3325 }
3326 }
3327}
3328
Douglas Gregor19b7b152009-08-24 13:43:27 +00003329/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3330/// the volatile- and non-volatile-qualified assignment operators for the
3331/// given type to the candidate set.
3332static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3333 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00003334 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003335 unsigned NumArgs,
3336 OverloadCandidateSet &CandidateSet) {
3337 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00003338
Douglas Gregor19b7b152009-08-24 13:43:27 +00003339 // T& operator=(T&, T)
3340 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3341 ParamTypes[1] = T;
3342 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3343 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003344
Douglas Gregor19b7b152009-08-24 13:43:27 +00003345 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3346 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00003347 ParamTypes[0]
3348 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00003349 ParamTypes[1] = T;
3350 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00003351 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003352 }
3353}
Mike Stump1eb44332009-09-09 15:08:12 +00003354
Sebastian Redl9994a342009-10-25 17:03:50 +00003355/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3356/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003357static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3358 Qualifiers VRQuals;
3359 const RecordType *TyRec;
3360 if (const MemberPointerType *RHSMPType =
3361 ArgExpr->getType()->getAs<MemberPointerType>())
3362 TyRec = cast<RecordType>(RHSMPType->getClass());
3363 else
3364 TyRec = ArgExpr->getType()->getAs<RecordType>();
3365 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003366 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003367 VRQuals.addVolatile();
3368 VRQuals.addRestrict();
3369 return VRQuals;
3370 }
3371
3372 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00003373 if (!ClassDecl->hasDefinition())
3374 return VRQuals;
3375
John McCalleec51cf2010-01-20 00:46:10 +00003376 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00003377 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003378
John McCalleec51cf2010-01-20 00:46:10 +00003379 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003380 E = Conversions->end(); I != E; ++I) {
3381 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003382 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3383 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3384 CanTy = ResTypeRef->getPointeeType();
3385 // Need to go down the pointer/mempointer chain and add qualifiers
3386 // as see them.
3387 bool done = false;
3388 while (!done) {
3389 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3390 CanTy = ResTypePtr->getPointeeType();
3391 else if (const MemberPointerType *ResTypeMPtr =
3392 CanTy->getAs<MemberPointerType>())
3393 CanTy = ResTypeMPtr->getPointeeType();
3394 else
3395 done = true;
3396 if (CanTy.isVolatileQualified())
3397 VRQuals.addVolatile();
3398 if (CanTy.isRestrictQualified())
3399 VRQuals.addRestrict();
3400 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3401 return VRQuals;
3402 }
3403 }
3404 }
3405 return VRQuals;
3406}
3407
Douglas Gregor74253732008-11-19 15:42:04 +00003408/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3409/// operator overloads to the candidate set (C++ [over.built]), based
3410/// on the operator @p Op and the arguments given. For example, if the
3411/// operator is a binary '+', this routine might add "int
3412/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003413void
Mike Stump1eb44332009-09-09 15:08:12 +00003414Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003415 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00003416 Expr **Args, unsigned NumArgs,
3417 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003418 // The set of "promoted arithmetic types", which are the arithmetic
3419 // types are that preserved by promotion (C++ [over.built]p2). Note
3420 // that the first few of these types are the promoted integral
3421 // types; these types need to be first.
3422 // FIXME: What about complex?
3423 const unsigned FirstIntegralType = 0;
3424 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00003425 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003426 LastPromotedIntegralType = 13;
3427 const unsigned FirstPromotedArithmeticType = 7,
3428 LastPromotedArithmeticType = 16;
3429 const unsigned NumArithmeticTypes = 16;
3430 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00003431 Context.BoolTy, Context.CharTy, Context.WCharTy,
3432// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003433 Context.SignedCharTy, Context.ShortTy,
3434 Context.UnsignedCharTy, Context.UnsignedShortTy,
3435 Context.IntTy, Context.LongTy, Context.LongLongTy,
3436 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3437 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3438 };
Douglas Gregor652371a2009-10-21 22:01:30 +00003439 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3440 "Invalid first promoted integral type");
3441 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3442 == Context.UnsignedLongLongTy &&
3443 "Invalid last promoted integral type");
3444 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3445 "Invalid first promoted arithmetic type");
3446 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3447 == Context.LongDoubleTy &&
3448 "Invalid last promoted arithmetic type");
3449
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003450 // Find all of the types that the arguments can convert to, but only
3451 // if the operator we're looking at has built-in operator candidates
3452 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003453 Qualifiers VisibleTypeConversionsQuals;
3454 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003455 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3456 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3457
Douglas Gregor5842ba92009-08-24 15:23:48 +00003458 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003459 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3460 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00003461 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003462 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00003463 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003464 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor74253732008-11-19 15:42:04 +00003465 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003466 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregor573d9c32009-10-21 23:19:44 +00003467 OpLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003468 true,
3469 (Op == OO_Exclaim ||
3470 Op == OO_AmpAmp ||
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003471 Op == OO_PipePipe),
3472 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003473 }
3474
3475 bool isComparison = false;
3476 switch (Op) {
3477 case OO_None:
3478 case NUM_OVERLOADED_OPERATORS:
3479 assert(false && "Expected an overloaded operator");
3480 break;
3481
Douglas Gregor74253732008-11-19 15:42:04 +00003482 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00003483 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00003484 goto UnaryStar;
3485 else
3486 goto BinaryStar;
3487 break;
3488
3489 case OO_Plus: // '+' is either unary or binary
3490 if (NumArgs == 1)
3491 goto UnaryPlus;
3492 else
3493 goto BinaryPlus;
3494 break;
3495
3496 case OO_Minus: // '-' is either unary or binary
3497 if (NumArgs == 1)
3498 goto UnaryMinus;
3499 else
3500 goto BinaryMinus;
3501 break;
3502
3503 case OO_Amp: // '&' is either unary or binary
3504 if (NumArgs == 1)
3505 goto UnaryAmp;
3506 else
3507 goto BinaryAmp;
3508
3509 case OO_PlusPlus:
3510 case OO_MinusMinus:
3511 // C++ [over.built]p3:
3512 //
3513 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3514 // is either volatile or empty, there exist candidate operator
3515 // functions of the form
3516 //
3517 // VQ T& operator++(VQ T&);
3518 // T operator++(VQ T&, int);
3519 //
3520 // C++ [over.built]p4:
3521 //
3522 // For every pair (T, VQ), where T is an arithmetic type other
3523 // than bool, and VQ is either volatile or empty, there exist
3524 // candidate operator functions of the form
3525 //
3526 // VQ T& operator--(VQ T&);
3527 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00003528 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00003529 Arith < NumArithmeticTypes; ++Arith) {
3530 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00003531 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003532 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00003533
3534 // Non-volatile version.
3535 if (NumArgs == 1)
3536 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3537 else
3538 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003539 // heuristic to reduce number of builtin candidates in the set.
3540 // Add volatile version only if there are conversions to a volatile type.
3541 if (VisibleTypeConversionsQuals.hasVolatile()) {
3542 // Volatile version
3543 ParamTypes[0]
3544 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3545 if (NumArgs == 1)
3546 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3547 else
3548 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3549 }
Douglas Gregor74253732008-11-19 15:42:04 +00003550 }
3551
3552 // C++ [over.built]p5:
3553 //
3554 // For every pair (T, VQ), where T is a cv-qualified or
3555 // cv-unqualified object type, and VQ is either volatile or
3556 // empty, there exist candidate operator functions of the form
3557 //
3558 // T*VQ& operator++(T*VQ&);
3559 // T*VQ& operator--(T*VQ&);
3560 // T* operator++(T*VQ&, int);
3561 // T* operator--(T*VQ&, int);
3562 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3563 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3564 // Skip pointer types that aren't pointers to object types.
Ted Kremenek6217b802009-07-29 21:53:49 +00003565 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00003566 continue;
3567
Mike Stump1eb44332009-09-09 15:08:12 +00003568 QualType ParamTypes[2] = {
3569 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00003570 };
Mike Stump1eb44332009-09-09 15:08:12 +00003571
Douglas Gregor74253732008-11-19 15:42:04 +00003572 // Without volatile
3573 if (NumArgs == 1)
3574 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3575 else
3576 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3577
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003578 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3579 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003580 // With volatile
John McCall0953e762009-09-24 19:53:00 +00003581 ParamTypes[0]
3582 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00003583 if (NumArgs == 1)
3584 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3585 else
3586 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3587 }
3588 }
3589 break;
3590
3591 UnaryStar:
3592 // C++ [over.built]p6:
3593 // For every cv-qualified or cv-unqualified object type T, there
3594 // exist candidate operator functions of the form
3595 //
3596 // T& operator*(T*);
3597 //
3598 // C++ [over.built]p7:
3599 // For every function type T, there exist candidate operator
3600 // functions of the form
3601 // T& operator*(T*);
3602 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3603 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3604 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00003605 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003606 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00003607 &ParamTy, Args, 1, CandidateSet);
3608 }
3609 break;
3610
3611 UnaryPlus:
3612 // C++ [over.built]p8:
3613 // For every type T, there exist candidate operator functions of
3614 // the form
3615 //
3616 // T* operator+(T*);
3617 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3618 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3619 QualType ParamTy = *Ptr;
3620 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3621 }
Mike Stump1eb44332009-09-09 15:08:12 +00003622
Douglas Gregor74253732008-11-19 15:42:04 +00003623 // Fall through
3624
3625 UnaryMinus:
3626 // C++ [over.built]p9:
3627 // For every promoted arithmetic type T, there exist candidate
3628 // operator functions of the form
3629 //
3630 // T operator+(T);
3631 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003632 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00003633 Arith < LastPromotedArithmeticType; ++Arith) {
3634 QualType ArithTy = ArithmeticTypes[Arith];
3635 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3636 }
3637 break;
3638
3639 case OO_Tilde:
3640 // C++ [over.built]p10:
3641 // For every promoted integral type T, there exist candidate
3642 // operator functions of the form
3643 //
3644 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003645 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00003646 Int < LastPromotedIntegralType; ++Int) {
3647 QualType IntTy = ArithmeticTypes[Int];
3648 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3649 }
3650 break;
3651
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003652 case OO_New:
3653 case OO_Delete:
3654 case OO_Array_New:
3655 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003656 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00003657 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003658 break;
3659
3660 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00003661 UnaryAmp:
3662 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003663 // C++ [over.match.oper]p3:
3664 // -- For the operator ',', the unary operator '&', or the
3665 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003666 break;
3667
Douglas Gregor19b7b152009-08-24 13:43:27 +00003668 case OO_EqualEqual:
3669 case OO_ExclaimEqual:
3670 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00003671 // For every pointer to member type T, there exist candidate operator
3672 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00003673 //
3674 // bool operator==(T,T);
3675 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00003676 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00003677 MemPtr = CandidateTypes.member_pointer_begin(),
3678 MemPtrEnd = CandidateTypes.member_pointer_end();
3679 MemPtr != MemPtrEnd;
3680 ++MemPtr) {
3681 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3682 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3683 }
Mike Stump1eb44332009-09-09 15:08:12 +00003684
Douglas Gregor19b7b152009-08-24 13:43:27 +00003685 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00003686
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003687 case OO_Less:
3688 case OO_Greater:
3689 case OO_LessEqual:
3690 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003691 // C++ [over.built]p15:
3692 //
3693 // For every pointer or enumeration type T, there exist
3694 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003695 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003696 // bool operator<(T, T);
3697 // bool operator>(T, T);
3698 // bool operator<=(T, T);
3699 // bool operator>=(T, T);
3700 // bool operator==(T, T);
3701 // bool operator!=(T, T);
3702 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3703 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3704 QualType ParamTypes[2] = { *Ptr, *Ptr };
3705 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3706 }
Mike Stump1eb44332009-09-09 15:08:12 +00003707 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003708 = CandidateTypes.enumeration_begin();
3709 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3710 QualType ParamTypes[2] = { *Enum, *Enum };
3711 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3712 }
3713
3714 // Fall through.
3715 isComparison = true;
3716
Douglas Gregor74253732008-11-19 15:42:04 +00003717 BinaryPlus:
3718 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003719 if (!isComparison) {
3720 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3721
3722 // C++ [over.built]p13:
3723 //
3724 // For every cv-qualified or cv-unqualified object type T
3725 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003726 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003727 // T* operator+(T*, ptrdiff_t);
3728 // T& operator[](T*, ptrdiff_t); [BELOW]
3729 // T* operator-(T*, ptrdiff_t);
3730 // T* operator+(ptrdiff_t, T*);
3731 // T& operator[](ptrdiff_t, T*); [BELOW]
3732 //
3733 // C++ [over.built]p14:
3734 //
3735 // For every T, where T is a pointer to object type, there
3736 // exist candidate operator functions of the form
3737 //
3738 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00003739 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003740 = CandidateTypes.pointer_begin();
3741 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3742 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3743
3744 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3745 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3746
3747 if (Op == OO_Plus) {
3748 // T* operator+(ptrdiff_t, T*);
3749 ParamTypes[0] = ParamTypes[1];
3750 ParamTypes[1] = *Ptr;
3751 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3752 } else {
3753 // ptrdiff_t operator-(T, T);
3754 ParamTypes[1] = *Ptr;
3755 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3756 Args, 2, CandidateSet);
3757 }
3758 }
3759 }
3760 // Fall through
3761
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003762 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00003763 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003764 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003765 // C++ [over.built]p12:
3766 //
3767 // For every pair of promoted arithmetic types L and R, there
3768 // exist candidate operator functions of the form
3769 //
3770 // LR operator*(L, R);
3771 // LR operator/(L, R);
3772 // LR operator+(L, R);
3773 // LR operator-(L, R);
3774 // bool operator<(L, R);
3775 // bool operator>(L, R);
3776 // bool operator<=(L, R);
3777 // bool operator>=(L, R);
3778 // bool operator==(L, R);
3779 // bool operator!=(L, R);
3780 //
3781 // where LR is the result of the usual arithmetic conversions
3782 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003783 //
3784 // C++ [over.built]p24:
3785 //
3786 // For every pair of promoted arithmetic types L and R, there exist
3787 // candidate operator functions of the form
3788 //
3789 // LR operator?(bool, L, R);
3790 //
3791 // where LR is the result of the usual arithmetic conversions
3792 // between types L and R.
3793 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003794 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003795 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003796 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003797 Right < LastPromotedArithmeticType; ++Right) {
3798 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00003799 QualType Result
3800 = isComparison
3801 ? Context.BoolTy
3802 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003803 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3804 }
3805 }
3806 break;
3807
3808 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00003809 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003810 case OO_Caret:
3811 case OO_Pipe:
3812 case OO_LessLess:
3813 case OO_GreaterGreater:
3814 // C++ [over.built]p17:
3815 //
3816 // For every pair of promoted integral types L and R, there
3817 // exist candidate operator functions of the form
3818 //
3819 // LR operator%(L, R);
3820 // LR operator&(L, R);
3821 // LR operator^(L, R);
3822 // LR operator|(L, R);
3823 // L operator<<(L, R);
3824 // L operator>>(L, R);
3825 //
3826 // where LR is the result of the usual arithmetic conversions
3827 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00003828 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003829 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003830 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003831 Right < LastPromotedIntegralType; ++Right) {
3832 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3833 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3834 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00003835 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003836 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3837 }
3838 }
3839 break;
3840
3841 case OO_Equal:
3842 // C++ [over.built]p20:
3843 //
3844 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00003845 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003846 // empty, there exist candidate operator functions of the form
3847 //
3848 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003849 for (BuiltinCandidateTypeSet::iterator
3850 Enum = CandidateTypes.enumeration_begin(),
3851 EnumEnd = CandidateTypes.enumeration_end();
3852 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00003853 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003854 CandidateSet);
3855 for (BuiltinCandidateTypeSet::iterator
3856 MemPtr = CandidateTypes.member_pointer_begin(),
3857 MemPtrEnd = CandidateTypes.member_pointer_end();
3858 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00003859 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003860 CandidateSet);
3861 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003862
3863 case OO_PlusEqual:
3864 case OO_MinusEqual:
3865 // C++ [over.built]p19:
3866 //
3867 // For every pair (T, VQ), where T is any type and VQ is either
3868 // volatile or empty, there exist candidate operator functions
3869 // of the form
3870 //
3871 // T*VQ& operator=(T*VQ&, T*);
3872 //
3873 // C++ [over.built]p21:
3874 //
3875 // For every pair (T, VQ), where T is a cv-qualified or
3876 // cv-unqualified object type and VQ is either volatile or
3877 // empty, there exist candidate operator functions of the form
3878 //
3879 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3880 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3881 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3882 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3883 QualType ParamTypes[2];
3884 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3885
3886 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003887 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003888 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3889 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003890
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003891 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3892 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003893 // volatile version
John McCall0953e762009-09-24 19:53:00 +00003894 ParamTypes[0]
3895 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003896 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3897 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003898 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003899 }
3900 // Fall through.
3901
3902 case OO_StarEqual:
3903 case OO_SlashEqual:
3904 // C++ [over.built]p18:
3905 //
3906 // For every triple (L, VQ, R), where L is an arithmetic type,
3907 // VQ is either volatile or empty, and R is a promoted
3908 // arithmetic type, there exist candidate operator functions of
3909 // the form
3910 //
3911 // VQ L& operator=(VQ L&, R);
3912 // VQ L& operator*=(VQ L&, R);
3913 // VQ L& operator/=(VQ L&, R);
3914 // VQ L& operator+=(VQ L&, R);
3915 // VQ L& operator-=(VQ L&, R);
3916 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003917 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003918 Right < LastPromotedArithmeticType; ++Right) {
3919 QualType ParamTypes[2];
3920 ParamTypes[1] = ArithmeticTypes[Right];
3921
3922 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003923 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003924 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3925 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003926
3927 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003928 if (VisibleTypeConversionsQuals.hasVolatile()) {
3929 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3930 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3931 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3932 /*IsAssigmentOperator=*/Op == OO_Equal);
3933 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003934 }
3935 }
3936 break;
3937
3938 case OO_PercentEqual:
3939 case OO_LessLessEqual:
3940 case OO_GreaterGreaterEqual:
3941 case OO_AmpEqual:
3942 case OO_CaretEqual:
3943 case OO_PipeEqual:
3944 // C++ [over.built]p22:
3945 //
3946 // For every triple (L, VQ, R), where L is an integral type, VQ
3947 // is either volatile or empty, and R is a promoted integral
3948 // type, there exist candidate operator functions of the form
3949 //
3950 // VQ L& operator%=(VQ L&, R);
3951 // VQ L& operator<<=(VQ L&, R);
3952 // VQ L& operator>>=(VQ L&, R);
3953 // VQ L& operator&=(VQ L&, R);
3954 // VQ L& operator^=(VQ L&, R);
3955 // VQ L& operator|=(VQ L&, R);
3956 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003957 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003958 Right < LastPromotedIntegralType; ++Right) {
3959 QualType ParamTypes[2];
3960 ParamTypes[1] = ArithmeticTypes[Right];
3961
3962 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003963 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003964 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00003965 if (VisibleTypeConversionsQuals.hasVolatile()) {
3966 // Add this built-in operator as a candidate (VQ is 'volatile').
3967 ParamTypes[0] = ArithmeticTypes[Left];
3968 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3969 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3970 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3971 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003972 }
3973 }
3974 break;
3975
Douglas Gregor74253732008-11-19 15:42:04 +00003976 case OO_Exclaim: {
3977 // C++ [over.operator]p23:
3978 //
3979 // There also exist candidate operator functions of the form
3980 //
Mike Stump1eb44332009-09-09 15:08:12 +00003981 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00003982 // bool operator&&(bool, bool); [BELOW]
3983 // bool operator||(bool, bool); [BELOW]
3984 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003985 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3986 /*IsAssignmentOperator=*/false,
3987 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00003988 break;
3989 }
3990
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003991 case OO_AmpAmp:
3992 case OO_PipePipe: {
3993 // C++ [over.operator]p23:
3994 //
3995 // There also exist candidate operator functions of the form
3996 //
Douglas Gregor74253732008-11-19 15:42:04 +00003997 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003998 // bool operator&&(bool, bool);
3999 // bool operator||(bool, bool);
4000 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004001 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4002 /*IsAssignmentOperator=*/false,
4003 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004004 break;
4005 }
4006
4007 case OO_Subscript:
4008 // C++ [over.built]p13:
4009 //
4010 // For every cv-qualified or cv-unqualified object type T there
4011 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004012 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004013 // T* operator+(T*, ptrdiff_t); [ABOVE]
4014 // T& operator[](T*, ptrdiff_t);
4015 // T* operator-(T*, ptrdiff_t); [ABOVE]
4016 // T* operator+(ptrdiff_t, T*); [ABOVE]
4017 // T& operator[](ptrdiff_t, T*);
4018 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4019 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4020 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00004021 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004022 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004023
4024 // T& operator[](T*, ptrdiff_t)
4025 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4026
4027 // T& operator[](ptrdiff_t, T*);
4028 ParamTypes[0] = ParamTypes[1];
4029 ParamTypes[1] = *Ptr;
4030 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4031 }
4032 break;
4033
4034 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004035 // C++ [over.built]p11:
4036 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4037 // C1 is the same type as C2 or is a derived class of C2, T is an object
4038 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4039 // there exist candidate operator functions of the form
4040 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4041 // where CV12 is the union of CV1 and CV2.
4042 {
4043 for (BuiltinCandidateTypeSet::iterator Ptr =
4044 CandidateTypes.pointer_begin();
4045 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4046 QualType C1Ty = (*Ptr);
4047 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004048 QualifierCollector Q1;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004049 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004050 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004051 if (!isa<RecordType>(C1))
4052 continue;
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004053 // heuristic to reduce number of builtin candidates in the set.
4054 // Add volatile/restrict version only if there are conversions to a
4055 // volatile/restrict type.
4056 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4057 continue;
4058 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4059 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004060 }
4061 for (BuiltinCandidateTypeSet::iterator
4062 MemPtr = CandidateTypes.member_pointer_begin(),
4063 MemPtrEnd = CandidateTypes.member_pointer_end();
4064 MemPtr != MemPtrEnd; ++MemPtr) {
4065 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4066 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00004067 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004068 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4069 break;
4070 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4071 // build CV12 T&
4072 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004073 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4074 T.isVolatileQualified())
4075 continue;
4076 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4077 T.isRestrictQualified())
4078 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004079 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004080 QualType ResultTy = Context.getLValueReferenceType(T);
4081 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4082 }
4083 }
4084 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004085 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004086
4087 case OO_Conditional:
4088 // Note that we don't consider the first argument, since it has been
4089 // contextually converted to bool long ago. The candidates below are
4090 // therefore added as binary.
4091 //
4092 // C++ [over.built]p24:
4093 // For every type T, where T is a pointer or pointer-to-member type,
4094 // there exist candidate operator functions of the form
4095 //
4096 // T operator?(bool, T, T);
4097 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004098 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4099 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4100 QualType ParamTypes[2] = { *Ptr, *Ptr };
4101 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4102 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00004103 for (BuiltinCandidateTypeSet::iterator Ptr =
4104 CandidateTypes.member_pointer_begin(),
4105 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4106 QualType ParamTypes[2] = { *Ptr, *Ptr };
4107 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4108 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004109 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004110 }
4111}
4112
Douglas Gregorfa047642009-02-04 00:32:51 +00004113/// \brief Add function candidates found via argument-dependent lookup
4114/// to the set of overloading candidates.
4115///
4116/// This routine performs argument-dependent name lookup based on the
4117/// given function name (which may also be an operator name) and adds
4118/// all of the overload candidates found by ADL to the overload
4119/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00004120void
Douglas Gregorfa047642009-02-04 00:32:51 +00004121Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00004122 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00004123 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00004124 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004125 OverloadCandidateSet& CandidateSet,
4126 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00004127 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00004128
John McCalla113e722010-01-26 06:04:06 +00004129 // FIXME: This approach for uniquing ADL results (and removing
4130 // redundant candidates from the set) relies on pointer-equality,
4131 // which means we need to key off the canonical decl. However,
4132 // always going back to the canonical decl might not get us the
4133 // right set of default arguments. What default arguments are
4134 // we supposed to consider on ADL candidates, anyway?
4135
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004136 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00004137 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00004138
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004139 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004140 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4141 CandEnd = CandidateSet.end();
4142 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00004143 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00004144 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00004145 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00004146 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00004147 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004148
4149 // For each of the ADL candidates we found, add it to the overload
4150 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00004151 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00004152 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00004153 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00004154 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004155 continue;
4156
John McCall9aa472c2010-03-19 07:35:19 +00004157 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004158 false, false, PartialOverloading);
4159 } else
John McCall6e266892010-01-26 03:27:55 +00004160 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00004161 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004162 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00004163 }
Douglas Gregorfa047642009-02-04 00:32:51 +00004164}
4165
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004166/// isBetterOverloadCandidate - Determines whether the first overload
4167/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00004168bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004169Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCall5769d612010-02-08 23:07:23 +00004170 const OverloadCandidate& Cand2,
4171 SourceLocation Loc) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004172 // Define viable functions to be better candidates than non-viable
4173 // functions.
4174 if (!Cand2.Viable)
4175 return Cand1.Viable;
4176 else if (!Cand1.Viable)
4177 return false;
4178
Douglas Gregor88a35142008-12-22 05:46:06 +00004179 // C++ [over.match.best]p1:
4180 //
4181 // -- if F is a static member function, ICS1(F) is defined such
4182 // that ICS1(F) is neither better nor worse than ICS1(G) for
4183 // any function G, and, symmetrically, ICS1(G) is neither
4184 // better nor worse than ICS1(F).
4185 unsigned StartArg = 0;
4186 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4187 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004188
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004189 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00004190 // A viable function F1 is defined to be a better function than another
4191 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004192 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004193 unsigned NumArgs = Cand1.Conversions.size();
4194 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4195 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004196 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004197 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4198 Cand2.Conversions[ArgIdx])) {
4199 case ImplicitConversionSequence::Better:
4200 // Cand1 has a better conversion sequence.
4201 HasBetterConversion = true;
4202 break;
4203
4204 case ImplicitConversionSequence::Worse:
4205 // Cand1 can't be better than Cand2.
4206 return false;
4207
4208 case ImplicitConversionSequence::Indistinguishable:
4209 // Do nothing.
4210 break;
4211 }
4212 }
4213
Mike Stump1eb44332009-09-09 15:08:12 +00004214 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004215 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004216 if (HasBetterConversion)
4217 return true;
4218
Mike Stump1eb44332009-09-09 15:08:12 +00004219 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004220 // specialization, or, if not that,
4221 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4222 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4223 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004224
4225 // -- F1 and F2 are function template specializations, and the function
4226 // template for F1 is more specialized than the template for F2
4227 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004228 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00004229 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4230 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004231 if (FunctionTemplateDecl *BetterTemplate
4232 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4233 Cand2.Function->getPrimaryTemplate(),
John McCall5769d612010-02-08 23:07:23 +00004234 Loc,
Douglas Gregor5d7d3752009-09-14 23:02:14 +00004235 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4236 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004237 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004238
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004239 // -- the context is an initialization by user-defined conversion
4240 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4241 // from the return type of F1 to the destination type (i.e.,
4242 // the type of the entity being initialized) is a better
4243 // conversion sequence than the standard conversion sequence
4244 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00004245 if (Cand1.Function && Cand2.Function &&
4246 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004247 isa<CXXConversionDecl>(Cand2.Function)) {
4248 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4249 Cand2.FinalConversion)) {
4250 case ImplicitConversionSequence::Better:
4251 // Cand1 has a better conversion sequence.
4252 return true;
4253
4254 case ImplicitConversionSequence::Worse:
4255 // Cand1 can't be better than Cand2.
4256 return false;
4257
4258 case ImplicitConversionSequence::Indistinguishable:
4259 // Do nothing
4260 break;
4261 }
4262 }
4263
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004264 return false;
4265}
4266
Mike Stump1eb44332009-09-09 15:08:12 +00004267/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00004268/// within an overload candidate set.
4269///
4270/// \param CandidateSet the set of candidate functions.
4271///
4272/// \param Loc the location of the function name (or operator symbol) for
4273/// which overload resolution occurs.
4274///
Mike Stump1eb44332009-09-09 15:08:12 +00004275/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00004276/// function, Best points to the candidate function found.
4277///
4278/// \returns The result of overload resolution.
Douglas Gregor20093b42009-12-09 23:02:17 +00004279OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4280 SourceLocation Loc,
4281 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004282 // Find the best viable function.
4283 Best = CandidateSet.end();
4284 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4285 Cand != CandidateSet.end(); ++Cand) {
4286 if (Cand->Viable) {
John McCall5769d612010-02-08 23:07:23 +00004287 if (Best == CandidateSet.end() ||
4288 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004289 Best = Cand;
4290 }
4291 }
4292
4293 // If we didn't find any viable functions, abort.
4294 if (Best == CandidateSet.end())
4295 return OR_No_Viable_Function;
4296
4297 // Make sure that this function is better than every other viable
4298 // function. If not, we have an ambiguity.
4299 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4300 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00004301 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004302 Cand != Best &&
John McCall5769d612010-02-08 23:07:23 +00004303 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004304 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004305 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004306 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004307 }
Mike Stump1eb44332009-09-09 15:08:12 +00004308
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004309 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004310 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00004311 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004312 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004313 return OR_Deleted;
4314
Douglas Gregore0762c92009-06-19 23:52:42 +00004315 // C++ [basic.def.odr]p2:
4316 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00004317 // when referred to from a potentially-evaluated expression. [Note: this
4318 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00004319 // (clause 13), user-defined conversions (12.3.2), allocation function for
4320 // placement new (5.3.4), as well as non-default initialization (8.5).
4321 if (Best->Function)
4322 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004323 return OR_Success;
4324}
4325
John McCall3c80f572010-01-12 02:15:36 +00004326namespace {
4327
4328enum OverloadCandidateKind {
4329 oc_function,
4330 oc_method,
4331 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00004332 oc_function_template,
4333 oc_method_template,
4334 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00004335 oc_implicit_default_constructor,
4336 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00004337 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00004338};
4339
John McCall220ccbf2010-01-13 00:25:19 +00004340OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4341 FunctionDecl *Fn,
4342 std::string &Description) {
4343 bool isTemplate = false;
4344
4345 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4346 isTemplate = true;
4347 Description = S.getTemplateArgumentBindingsText(
4348 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4349 }
John McCallb1622a12010-01-06 09:43:14 +00004350
4351 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00004352 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00004353 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00004354
John McCall3c80f572010-01-12 02:15:36 +00004355 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4356 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00004357 }
4358
4359 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4360 // This actually gets spelled 'candidate function' for now, but
4361 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00004362 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00004363 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00004364
4365 assert(Meth->isCopyAssignment()
4366 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00004367 return oc_implicit_copy_assignment;
4368 }
4369
John McCall220ccbf2010-01-13 00:25:19 +00004370 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00004371}
4372
4373} // end anonymous namespace
4374
4375// Notes the location of an overload candidate.
4376void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00004377 std::string FnDesc;
4378 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4379 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4380 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00004381}
4382
John McCall1d318332010-01-12 00:44:57 +00004383/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4384/// "lead" diagnostic; it will be given two arguments, the source and
4385/// target types of the conversion.
4386void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4387 SourceLocation CaretLoc,
4388 const PartialDiagnostic &PDiag) {
4389 Diag(CaretLoc, PDiag)
4390 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4391 for (AmbiguousConversionSequence::const_iterator
4392 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4393 NoteOverloadCandidate(*I);
4394 }
John McCall81201622010-01-08 04:41:39 +00004395}
4396
John McCall1d318332010-01-12 00:44:57 +00004397namespace {
4398
John McCalladbb8f82010-01-13 09:16:55 +00004399void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4400 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4401 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00004402 assert(Cand->Function && "for now, candidate must be a function");
4403 FunctionDecl *Fn = Cand->Function;
4404
4405 // There's a conversion slot for the object argument if this is a
4406 // non-constructor method. Note that 'I' corresponds the
4407 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00004408 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00004409 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00004410 if (I == 0)
4411 isObjectArgument = true;
4412 else
4413 I--;
John McCall220ccbf2010-01-13 00:25:19 +00004414 }
4415
John McCall220ccbf2010-01-13 00:25:19 +00004416 std::string FnDesc;
4417 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4418
John McCalladbb8f82010-01-13 09:16:55 +00004419 Expr *FromExpr = Conv.Bad.FromExpr;
4420 QualType FromTy = Conv.Bad.getFromType();
4421 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00004422
John McCall5920dbb2010-02-02 02:42:52 +00004423 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00004424 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00004425 Expr *E = FromExpr->IgnoreParens();
4426 if (isa<UnaryOperator>(E))
4427 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00004428 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00004429
4430 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
4431 << (unsigned) FnKind << FnDesc
4432 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4433 << ToTy << Name << I+1;
4434 return;
4435 }
4436
John McCall258b2032010-01-23 08:10:49 +00004437 // Do some hand-waving analysis to see if the non-viability is due
4438 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00004439 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4440 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4441 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4442 CToTy = RT->getPointeeType();
4443 else {
4444 // TODO: detect and diagnose the full richness of const mismatches.
4445 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4446 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4447 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4448 }
4449
4450 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4451 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4452 // It is dumb that we have to do this here.
4453 while (isa<ArrayType>(CFromTy))
4454 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4455 while (isa<ArrayType>(CToTy))
4456 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4457
4458 Qualifiers FromQs = CFromTy.getQualifiers();
4459 Qualifiers ToQs = CToTy.getQualifiers();
4460
4461 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4462 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4463 << (unsigned) FnKind << FnDesc
4464 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4465 << FromTy
4466 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4467 << (unsigned) isObjectArgument << I+1;
4468 return;
4469 }
4470
4471 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4472 assert(CVR && "unexpected qualifiers mismatch");
4473
4474 if (isObjectArgument) {
4475 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4476 << (unsigned) FnKind << FnDesc
4477 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4478 << FromTy << (CVR - 1);
4479 } else {
4480 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4481 << (unsigned) FnKind << FnDesc
4482 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4483 << FromTy << (CVR - 1) << I+1;
4484 }
4485 return;
4486 }
4487
John McCall258b2032010-01-23 08:10:49 +00004488 // Diagnose references or pointers to incomplete types differently,
4489 // since it's far from impossible that the incompleteness triggered
4490 // the failure.
4491 QualType TempFromTy = FromTy.getNonReferenceType();
4492 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
4493 TempFromTy = PTy->getPointeeType();
4494 if (TempFromTy->isIncompleteType()) {
4495 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
4496 << (unsigned) FnKind << FnDesc
4497 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4498 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4499 return;
4500 }
4501
John McCall651f3ee2010-01-14 03:28:57 +00004502 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00004503 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4504 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00004505 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00004506 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00004507}
4508
4509void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4510 unsigned NumFormalArgs) {
4511 // TODO: treat calls to a missing default constructor as a special case
4512
4513 FunctionDecl *Fn = Cand->Function;
4514 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4515
4516 unsigned MinParams = Fn->getMinRequiredArguments();
4517
4518 // at least / at most / exactly
4519 unsigned mode, modeCount;
4520 if (NumFormalArgs < MinParams) {
4521 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4522 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4523 mode = 0; // "at least"
4524 else
4525 mode = 2; // "exactly"
4526 modeCount = MinParams;
4527 } else {
4528 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4529 if (MinParams != FnTy->getNumArgs())
4530 mode = 1; // "at most"
4531 else
4532 mode = 2; // "exactly"
4533 modeCount = FnTy->getNumArgs();
4534 }
4535
4536 std::string Description;
4537 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4538
4539 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4540 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00004541}
4542
John McCall342fec42010-02-01 18:53:26 +00004543/// Diagnose a failed template-argument deduction.
4544void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
4545 Expr **Args, unsigned NumArgs) {
4546 FunctionDecl *Fn = Cand->Function; // pattern
4547
4548 TemplateParameter Param = TemplateParameter::getFromOpaqueValue(
4549 Cand->DeductionFailure.TemplateParameter);
4550
4551 switch (Cand->DeductionFailure.Result) {
4552 case Sema::TDK_Success:
4553 llvm_unreachable("TDK_success while diagnosing bad deduction");
4554
4555 case Sema::TDK_Incomplete: {
4556 NamedDecl *ParamD;
4557 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
4558 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
4559 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
4560 assert(ParamD && "no parameter found for incomplete deduction result");
4561 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
4562 << ParamD->getDeclName();
4563 return;
4564 }
4565
4566 // TODO: diagnose these individually, then kill off
4567 // note_ovl_candidate_bad_deduction, which is uselessly vague.
4568 case Sema::TDK_InstantiationDepth:
4569 case Sema::TDK_Inconsistent:
4570 case Sema::TDK_InconsistentQuals:
4571 case Sema::TDK_SubstitutionFailure:
4572 case Sema::TDK_NonDeducedMismatch:
4573 case Sema::TDK_TooManyArguments:
4574 case Sema::TDK_TooFewArguments:
4575 case Sema::TDK_InvalidExplicitArguments:
4576 case Sema::TDK_FailedOverloadResolution:
4577 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
4578 return;
4579 }
4580}
4581
4582/// Generates a 'note' diagnostic for an overload candidate. We've
4583/// already generated a primary error at the call site.
4584///
4585/// It really does need to be a single diagnostic with its caret
4586/// pointed at the candidate declaration. Yes, this creates some
4587/// major challenges of technical writing. Yes, this makes pointing
4588/// out problems with specific arguments quite awkward. It's still
4589/// better than generating twenty screens of text for every failed
4590/// overload.
4591///
4592/// It would be great to be able to express per-candidate problems
4593/// more richly for those diagnostic clients that cared, but we'd
4594/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00004595void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4596 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00004597 FunctionDecl *Fn = Cand->Function;
4598
John McCall81201622010-01-08 04:41:39 +00004599 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00004600 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00004601 std::string FnDesc;
4602 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00004603
4604 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00004605 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00004606 return;
John McCall81201622010-01-08 04:41:39 +00004607 }
4608
John McCall220ccbf2010-01-13 00:25:19 +00004609 // We don't really have anything else to say about viable candidates.
4610 if (Cand->Viable) {
4611 S.NoteOverloadCandidate(Fn);
4612 return;
4613 }
John McCall1d318332010-01-12 00:44:57 +00004614
John McCalladbb8f82010-01-13 09:16:55 +00004615 switch (Cand->FailureKind) {
4616 case ovl_fail_too_many_arguments:
4617 case ovl_fail_too_few_arguments:
4618 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00004619
John McCalladbb8f82010-01-13 09:16:55 +00004620 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00004621 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
4622
John McCall717e8912010-01-23 05:17:32 +00004623 case ovl_fail_trivial_conversion:
4624 case ovl_fail_bad_final_conversion:
John McCalladbb8f82010-01-13 09:16:55 +00004625 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00004626
John McCallb1bdc622010-02-25 01:37:24 +00004627 case ovl_fail_bad_conversion: {
4628 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
4629 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00004630 if (Cand->Conversions[I].isBad())
4631 return DiagnoseBadConversion(S, Cand, I);
4632
4633 // FIXME: this currently happens when we're called from SemaInit
4634 // when user-conversion overload fails. Figure out how to handle
4635 // those conditions and diagnose them well.
4636 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00004637 }
John McCallb1bdc622010-02-25 01:37:24 +00004638 }
John McCalla1d7d622010-01-08 00:58:21 +00004639}
4640
4641void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4642 // Desugar the type of the surrogate down to a function type,
4643 // retaining as many typedefs as possible while still showing
4644 // the function type (and, therefore, its parameter types).
4645 QualType FnType = Cand->Surrogate->getConversionType();
4646 bool isLValueReference = false;
4647 bool isRValueReference = false;
4648 bool isPointer = false;
4649 if (const LValueReferenceType *FnTypeRef =
4650 FnType->getAs<LValueReferenceType>()) {
4651 FnType = FnTypeRef->getPointeeType();
4652 isLValueReference = true;
4653 } else if (const RValueReferenceType *FnTypeRef =
4654 FnType->getAs<RValueReferenceType>()) {
4655 FnType = FnTypeRef->getPointeeType();
4656 isRValueReference = true;
4657 }
4658 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4659 FnType = FnTypePtr->getPointeeType();
4660 isPointer = true;
4661 }
4662 // Desugar down to a function type.
4663 FnType = QualType(FnType->getAs<FunctionType>(), 0);
4664 // Reconstruct the pointer/reference as appropriate.
4665 if (isPointer) FnType = S.Context.getPointerType(FnType);
4666 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
4667 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
4668
4669 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
4670 << FnType;
4671}
4672
4673void NoteBuiltinOperatorCandidate(Sema &S,
4674 const char *Opc,
4675 SourceLocation OpLoc,
4676 OverloadCandidate *Cand) {
4677 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
4678 std::string TypeStr("operator");
4679 TypeStr += Opc;
4680 TypeStr += "(";
4681 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4682 if (Cand->Conversions.size() == 1) {
4683 TypeStr += ")";
4684 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
4685 } else {
4686 TypeStr += ", ";
4687 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4688 TypeStr += ")";
4689 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
4690 }
4691}
4692
4693void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
4694 OverloadCandidate *Cand) {
4695 unsigned NoOperands = Cand->Conversions.size();
4696 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4697 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00004698 if (ICS.isBad()) break; // all meaningless after first invalid
4699 if (!ICS.isAmbiguous()) continue;
4700
4701 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004702 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00004703 }
4704}
4705
John McCall1b77e732010-01-15 23:32:50 +00004706SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
4707 if (Cand->Function)
4708 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00004709 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00004710 return Cand->Surrogate->getLocation();
4711 return SourceLocation();
4712}
4713
John McCallbf65c0b2010-01-12 00:48:53 +00004714struct CompareOverloadCandidatesForDisplay {
4715 Sema &S;
4716 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00004717
4718 bool operator()(const OverloadCandidate *L,
4719 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00004720 // Fast-path this check.
4721 if (L == R) return false;
4722
John McCall81201622010-01-08 04:41:39 +00004723 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00004724 if (L->Viable) {
4725 if (!R->Viable) return true;
4726
4727 // TODO: introduce a tri-valued comparison for overload
4728 // candidates. Would be more worthwhile if we had a sort
4729 // that could exploit it.
John McCall5769d612010-02-08 23:07:23 +00004730 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
4731 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00004732 } else if (R->Viable)
4733 return false;
John McCall81201622010-01-08 04:41:39 +00004734
John McCall1b77e732010-01-15 23:32:50 +00004735 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00004736
John McCall1b77e732010-01-15 23:32:50 +00004737 // Criteria by which we can sort non-viable candidates:
4738 if (!L->Viable) {
4739 // 1. Arity mismatches come after other candidates.
4740 if (L->FailureKind == ovl_fail_too_many_arguments ||
4741 L->FailureKind == ovl_fail_too_few_arguments)
4742 return false;
4743 if (R->FailureKind == ovl_fail_too_many_arguments ||
4744 R->FailureKind == ovl_fail_too_few_arguments)
4745 return true;
John McCall81201622010-01-08 04:41:39 +00004746
John McCall717e8912010-01-23 05:17:32 +00004747 // 2. Bad conversions come first and are ordered by the number
4748 // of bad conversions and quality of good conversions.
4749 if (L->FailureKind == ovl_fail_bad_conversion) {
4750 if (R->FailureKind != ovl_fail_bad_conversion)
4751 return true;
4752
4753 // If there's any ordering between the defined conversions...
4754 // FIXME: this might not be transitive.
4755 assert(L->Conversions.size() == R->Conversions.size());
4756
4757 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00004758 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
4759 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall717e8912010-01-23 05:17:32 +00004760 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
4761 R->Conversions[I])) {
4762 case ImplicitConversionSequence::Better:
4763 leftBetter++;
4764 break;
4765
4766 case ImplicitConversionSequence::Worse:
4767 leftBetter--;
4768 break;
4769
4770 case ImplicitConversionSequence::Indistinguishable:
4771 break;
4772 }
4773 }
4774 if (leftBetter > 0) return true;
4775 if (leftBetter < 0) return false;
4776
4777 } else if (R->FailureKind == ovl_fail_bad_conversion)
4778 return false;
4779
John McCall1b77e732010-01-15 23:32:50 +00004780 // TODO: others?
4781 }
4782
4783 // Sort everything else by location.
4784 SourceLocation LLoc = GetLocationForCandidate(L);
4785 SourceLocation RLoc = GetLocationForCandidate(R);
4786
4787 // Put candidates without locations (e.g. builtins) at the end.
4788 if (LLoc.isInvalid()) return false;
4789 if (RLoc.isInvalid()) return true;
4790
4791 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00004792 }
4793};
4794
John McCall717e8912010-01-23 05:17:32 +00004795/// CompleteNonViableCandidate - Normally, overload resolution only
4796/// computes up to the first
4797void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
4798 Expr **Args, unsigned NumArgs) {
4799 assert(!Cand->Viable);
4800
4801 // Don't do anything on failures other than bad conversion.
4802 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
4803
4804 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00004805 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00004806 unsigned ConvCount = Cand->Conversions.size();
4807 while (true) {
4808 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
4809 ConvIdx++;
4810 if (Cand->Conversions[ConvIdx - 1].isBad())
4811 break;
4812 }
4813
4814 if (ConvIdx == ConvCount)
4815 return;
4816
John McCallb1bdc622010-02-25 01:37:24 +00004817 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
4818 "remaining conversion is initialized?");
4819
John McCall717e8912010-01-23 05:17:32 +00004820 // FIXME: these should probably be preserved from the overload
4821 // operation somehow.
4822 bool SuppressUserConversions = false;
4823 bool ForceRValue = false;
4824
4825 const FunctionProtoType* Proto;
4826 unsigned ArgIdx = ConvIdx;
4827
4828 if (Cand->IsSurrogate) {
4829 QualType ConvType
4830 = Cand->Surrogate->getConversionType().getNonReferenceType();
4831 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4832 ConvType = ConvPtrType->getPointeeType();
4833 Proto = ConvType->getAs<FunctionProtoType>();
4834 ArgIdx--;
4835 } else if (Cand->Function) {
4836 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
4837 if (isa<CXXMethodDecl>(Cand->Function) &&
4838 !isa<CXXConstructorDecl>(Cand->Function))
4839 ArgIdx--;
4840 } else {
4841 // Builtin binary operator with a bad first conversion.
4842 assert(ConvCount <= 3);
4843 for (; ConvIdx != ConvCount; ++ConvIdx)
4844 Cand->Conversions[ConvIdx]
4845 = S.TryCopyInitialization(Args[ConvIdx],
4846 Cand->BuiltinTypes.ParamTypes[ConvIdx],
4847 SuppressUserConversions, ForceRValue,
4848 /*InOverloadResolution*/ true);
4849 return;
4850 }
4851
4852 // Fill in the rest of the conversions.
4853 unsigned NumArgsInProto = Proto->getNumArgs();
4854 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
4855 if (ArgIdx < NumArgsInProto)
4856 Cand->Conversions[ConvIdx]
4857 = S.TryCopyInitialization(Args[ArgIdx], Proto->getArgType(ArgIdx),
4858 SuppressUserConversions, ForceRValue,
4859 /*InOverloadResolution=*/true);
4860 else
4861 Cand->Conversions[ConvIdx].setEllipsis();
4862 }
4863}
4864
John McCalla1d7d622010-01-08 00:58:21 +00004865} // end anonymous namespace
4866
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004867/// PrintOverloadCandidates - When overload resolution fails, prints
4868/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00004869/// set.
Mike Stump1eb44332009-09-09 15:08:12 +00004870void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004871Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall81201622010-01-08 04:41:39 +00004872 OverloadCandidateDisplayKind OCD,
John McCallcbce6062010-01-12 07:18:19 +00004873 Expr **Args, unsigned NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004874 const char *Opc,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00004875 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00004876 // Sort the candidates by viability and position. Sorting directly would
4877 // be prohibitive, so we make a set of pointers and sort those.
4878 llvm::SmallVector<OverloadCandidate*, 32> Cands;
4879 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
4880 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4881 LastCand = CandidateSet.end();
John McCall717e8912010-01-23 05:17:32 +00004882 Cand != LastCand; ++Cand) {
4883 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00004884 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00004885 else if (OCD == OCD_AllCandidates) {
4886 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
4887 Cands.push_back(Cand);
4888 }
4889 }
4890
John McCallbf65c0b2010-01-12 00:48:53 +00004891 std::sort(Cands.begin(), Cands.end(),
4892 CompareOverloadCandidatesForDisplay(*this));
John McCall81201622010-01-08 04:41:39 +00004893
John McCall1d318332010-01-12 00:44:57 +00004894 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00004895
John McCall81201622010-01-08 04:41:39 +00004896 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
4897 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
4898 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00004899
John McCalla1d7d622010-01-08 00:58:21 +00004900 if (Cand->Function)
John McCall220ccbf2010-01-13 00:25:19 +00004901 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00004902 else if (Cand->IsSurrogate)
4903 NoteSurrogateCandidate(*this, Cand);
4904
4905 // This a builtin candidate. We do not, in general, want to list
4906 // every possible builtin candidate.
John McCall1d318332010-01-12 00:44:57 +00004907 else if (Cand->Viable) {
4908 // Generally we only see ambiguities including viable builtin
4909 // operators if overload resolution got screwed up by an
4910 // ambiguous user-defined conversion.
4911 //
4912 // FIXME: It's quite possible for different conversions to see
4913 // different ambiguities, though.
4914 if (!ReportedAmbiguousConversions) {
4915 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
4916 ReportedAmbiguousConversions = true;
4917 }
John McCalla1d7d622010-01-08 00:58:21 +00004918
John McCall1d318332010-01-12 00:44:57 +00004919 // If this is a viable builtin, print it.
John McCalla1d7d622010-01-08 00:58:21 +00004920 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004921 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004922 }
4923}
4924
John McCall9aa472c2010-03-19 07:35:19 +00004925static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCallc373d482010-01-27 01:50:18 +00004926 if (isa<UnresolvedLookupExpr>(E))
John McCall9aa472c2010-03-19 07:35:19 +00004927 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00004928
John McCall9aa472c2010-03-19 07:35:19 +00004929 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00004930}
4931
Douglas Gregor904eed32008-11-10 20:40:00 +00004932/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4933/// an overloaded function (C++ [over.over]), where @p From is an
4934/// expression with overloaded function type and @p ToType is the type
4935/// we're trying to resolve to. For example:
4936///
4937/// @code
4938/// int f(double);
4939/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00004940///
Douglas Gregor904eed32008-11-10 20:40:00 +00004941/// int (*pfd)(double) = f; // selects f(double)
4942/// @endcode
4943///
4944/// This routine returns the resulting FunctionDecl if it could be
4945/// resolved, and NULL otherwise. When @p Complain is true, this
4946/// routine will emit diagnostics if there is an error.
4947FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00004948Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall6bb80172010-03-30 21:47:33 +00004949 bool Complain,
4950 DeclAccessPair &FoundResult) {
Douglas Gregor904eed32008-11-10 20:40:00 +00004951 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00004952 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00004953 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00004954 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004955 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00004956 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00004957 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00004958 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00004959 FunctionType = MemTypePtr->getPointeeType();
4960 IsMember = true;
4961 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004962
4963 // We only look at pointers or references to functions.
Douglas Gregor72e771f2009-07-09 17:16:51 +00004964 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor83314aa2009-07-08 20:55:45 +00004965 if (!FunctionType->isFunctionType())
Douglas Gregor904eed32008-11-10 20:40:00 +00004966 return 0;
4967
4968 // Find the actual overloaded function declaration.
John McCall7bb12da2010-02-02 06:20:04 +00004969 if (From->getType() != Context.OverloadTy)
4970 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004971
Douglas Gregor904eed32008-11-10 20:40:00 +00004972 // C++ [over.over]p1:
4973 // [...] [Note: any redundant set of parentheses surrounding the
4974 // overloaded function name is ignored (5.1). ]
Douglas Gregor904eed32008-11-10 20:40:00 +00004975 // C++ [over.over]p1:
4976 // [...] The overloaded function name can be preceded by the &
4977 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00004978 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
4979 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
4980 if (OvlExpr->hasExplicitTemplateArgs()) {
4981 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
4982 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregor904eed32008-11-10 20:40:00 +00004983 }
4984
Douglas Gregor904eed32008-11-10 20:40:00 +00004985 // Look through all of the overloaded functions, searching for one
4986 // whose type matches exactly.
John McCall9aa472c2010-03-19 07:35:19 +00004987 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004988 bool FoundNonTemplateFunction = false;
John McCall7bb12da2010-02-02 06:20:04 +00004989 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
4990 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00004991 // Look through any using declarations to find the underlying function.
4992 NamedDecl *Fn = (*I)->getUnderlyingDecl();
4993
Douglas Gregor904eed32008-11-10 20:40:00 +00004994 // C++ [over.over]p3:
4995 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00004996 // targets of type "pointer-to-function" or "reference-to-function."
4997 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00004998 // type "pointer-to-member-function."
4999 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00005000
Mike Stump1eb44332009-09-09 15:08:12 +00005001 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00005002 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00005003 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00005004 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00005005 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00005006 // static when converting to member pointer.
5007 if (Method->isStatic() == IsMember)
5008 continue;
5009 } else if (IsMember)
5010 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00005011
Douglas Gregor00aeb522009-07-08 23:33:52 +00005012 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005013 // If the name is a function template, template argument deduction is
5014 // done (14.8.2.2), and if the argument deduction succeeds, the
5015 // resulting template argument list is used to generate a single
5016 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00005017 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005018 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00005019 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00005020 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor83314aa2009-07-08 20:55:45 +00005021 if (TemplateDeductionResult Result
John McCall7bb12da2010-02-02 06:20:04 +00005022 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00005023 FunctionType, Specialization, Info)) {
5024 // FIXME: make a note of the failed deduction for diagnostics.
5025 (void)Result;
5026 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005027 // FIXME: If the match isn't exact, shouldn't we just drop this as
5028 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00005029 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00005030 == Context.getCanonicalType(Specialization->getType()));
John McCall9aa472c2010-03-19 07:35:19 +00005031 Matches.push_back(std::make_pair(I.getPair(),
5032 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor83314aa2009-07-08 20:55:45 +00005033 }
John McCallba135432009-11-21 08:51:07 +00005034
5035 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00005036 }
Mike Stump1eb44332009-09-09 15:08:12 +00005037
Chandler Carruthbd647292009-12-29 06:17:27 +00005038 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00005039 // Skip non-static functions when converting to pointer, and static
5040 // when converting to member pointer.
5041 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00005042 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005043
5044 // If we have explicit template arguments, skip non-templates.
John McCall7bb12da2010-02-02 06:20:04 +00005045 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005046 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00005047 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00005048 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00005049
Chandler Carruthbd647292009-12-29 06:17:27 +00005050 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00005051 QualType ResultTy;
5052 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5053 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5054 ResultTy)) {
John McCall9aa472c2010-03-19 07:35:19 +00005055 Matches.push_back(std::make_pair(I.getPair(),
5056 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00005057 FoundNonTemplateFunction = true;
5058 }
Mike Stump1eb44332009-09-09 15:08:12 +00005059 }
Douglas Gregor904eed32008-11-10 20:40:00 +00005060 }
5061
Douglas Gregor00aeb522009-07-08 23:33:52 +00005062 // If there were 0 or 1 matches, we're done.
5063 if (Matches.empty())
5064 return 0;
Sebastian Redl07ab2022009-10-17 21:12:09 +00005065 else if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00005066 FunctionDecl *Result = Matches[0].second;
John McCall6bb80172010-03-30 21:47:33 +00005067 FoundResult = Matches[0].first;
Sebastian Redl07ab2022009-10-17 21:12:09 +00005068 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCallc373d482010-01-27 01:50:18 +00005069 if (Complain)
John McCall6bb80172010-03-30 21:47:33 +00005070 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redl07ab2022009-10-17 21:12:09 +00005071 return Result;
5072 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00005073
5074 // C++ [over.over]p4:
5075 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00005076 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005077 // [...] and any given function template specialization F1 is
5078 // eliminated if the set contains a second function template
5079 // specialization whose function template is more specialized
5080 // than the function template of F1 according to the partial
5081 // ordering rules of 14.5.5.2.
5082
5083 // The algorithm specified above is quadratic. We instead use a
5084 // two-pass algorithm (similar to the one used to identify the
5085 // best viable function in an overload set) that identifies the
5086 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00005087
5088 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5089 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5090 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCallc373d482010-01-27 01:50:18 +00005091
5092 UnresolvedSetIterator Result =
John McCall9aa472c2010-03-19 07:35:19 +00005093 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00005094 TPOC_Other, From->getLocStart(),
5095 PDiag(),
5096 PDiag(diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00005097 << Matches[0].second->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00005098 PDiag(diag::note_ovl_candidate)
5099 << (unsigned) oc_function_template);
John McCall9aa472c2010-03-19 07:35:19 +00005100 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCallc373d482010-01-27 01:50:18 +00005101 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall6bb80172010-03-30 21:47:33 +00005102 FoundResult = Matches[Result - MatchesCopy.begin()].first;
5103 if (Complain)
5104 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCallc373d482010-01-27 01:50:18 +00005105 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00005106 }
Mike Stump1eb44332009-09-09 15:08:12 +00005107
Douglas Gregor312a2022009-09-26 03:56:17 +00005108 // [...] any function template specializations in the set are
5109 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00005110 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCall9aa472c2010-03-19 07:35:19 +00005111 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCallc373d482010-01-27 01:50:18 +00005112 ++I;
5113 else {
John McCall9aa472c2010-03-19 07:35:19 +00005114 Matches[I] = Matches[--N];
5115 Matches.set_size(N);
John McCallc373d482010-01-27 01:50:18 +00005116 }
5117 }
Douglas Gregor312a2022009-09-26 03:56:17 +00005118
Mike Stump1eb44332009-09-09 15:08:12 +00005119 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00005120 // selected function.
John McCallc373d482010-01-27 01:50:18 +00005121 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00005122 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall6bb80172010-03-30 21:47:33 +00005123 FoundResult = Matches[0].first;
John McCallc373d482010-01-27 01:50:18 +00005124 if (Complain)
John McCall9aa472c2010-03-19 07:35:19 +00005125 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
5126 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redl07ab2022009-10-17 21:12:09 +00005127 }
Mike Stump1eb44332009-09-09 15:08:12 +00005128
Douglas Gregor00aeb522009-07-08 23:33:52 +00005129 // FIXME: We should probably return the same thing that BestViableFunction
5130 // returns (even if we issue the diagnostics here).
5131 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00005132 << Matches[0].second->getDeclName();
5133 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5134 NoteOverloadCandidate(Matches[I].second);
Douglas Gregor904eed32008-11-10 20:40:00 +00005135 return 0;
5136}
5137
Douglas Gregor4b52e252009-12-21 23:17:24 +00005138/// \brief Given an expression that refers to an overloaded function, try to
5139/// resolve that overloaded function expression down to a single function.
5140///
5141/// This routine can only resolve template-ids that refer to a single function
5142/// template, where that template-id refers to a single template whose template
5143/// arguments are either provided by the template-id or have defaults,
5144/// as described in C++0x [temp.arg.explicit]p3.
5145FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5146 // C++ [over.over]p1:
5147 // [...] [Note: any redundant set of parentheses surrounding the
5148 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00005149 // C++ [over.over]p1:
5150 // [...] The overloaded function name can be preceded by the &
5151 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00005152
5153 if (From->getType() != Context.OverloadTy)
5154 return 0;
5155
5156 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor4b52e252009-12-21 23:17:24 +00005157
5158 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00005159 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00005160 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00005161
5162 TemplateArgumentListInfo ExplicitTemplateArgs;
5163 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor4b52e252009-12-21 23:17:24 +00005164
5165 // Look through all of the overloaded functions, searching for one
5166 // whose type matches exactly.
5167 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00005168 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5169 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00005170 // C++0x [temp.arg.explicit]p3:
5171 // [...] In contexts where deduction is done and fails, or in contexts
5172 // where deduction is not done, if a template argument list is
5173 // specified and it, along with any default template arguments,
5174 // identifies a single function template specialization, then the
5175 // template-id is an lvalue for the function template specialization.
5176 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5177
5178 // C++ [over.over]p2:
5179 // If the name is a function template, template argument deduction is
5180 // done (14.8.2.2), and if the argument deduction succeeds, the
5181 // resulting template argument list is used to generate a single
5182 // function template specialization, which is added to the set of
5183 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00005184 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00005185 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00005186 if (TemplateDeductionResult Result
5187 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5188 Specialization, Info)) {
5189 // FIXME: make a note of the failed deduction for diagnostics.
5190 (void)Result;
5191 continue;
5192 }
5193
5194 // Multiple matches; we can't resolve to a single declaration.
5195 if (Matched)
5196 return 0;
5197
5198 Matched = Specialization;
5199 }
5200
5201 return Matched;
5202}
5203
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005204/// \brief Add a single candidate to the overload set.
5205static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00005206 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00005207 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005208 Expr **Args, unsigned NumArgs,
5209 OverloadCandidateSet &CandidateSet,
5210 bool PartialOverloading) {
John McCall9aa472c2010-03-19 07:35:19 +00005211 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00005212 if (isa<UsingShadowDecl>(Callee))
5213 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5214
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005215 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00005216 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall9aa472c2010-03-19 07:35:19 +00005217 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
John McCall86820f52010-01-26 01:37:31 +00005218 false, false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005219 return;
John McCallba135432009-11-21 08:51:07 +00005220 }
5221
5222 if (FunctionTemplateDecl *FuncTemplate
5223 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00005224 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
5225 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00005226 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00005227 return;
5228 }
5229
5230 assert(false && "unhandled case in overloaded call candidate");
5231
5232 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005233}
5234
5235/// \brief Add the overload candidates named by callee and/or found by argument
5236/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00005237void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005238 Expr **Args, unsigned NumArgs,
5239 OverloadCandidateSet &CandidateSet,
5240 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00005241
5242#ifndef NDEBUG
5243 // Verify that ArgumentDependentLookup is consistent with the rules
5244 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005245 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005246 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5247 // and let Y be the lookup set produced by argument dependent
5248 // lookup (defined as follows). If X contains
5249 //
5250 // -- a declaration of a class member, or
5251 //
5252 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00005253 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005254 //
5255 // -- a declaration that is neither a function or a function
5256 // template
5257 //
5258 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00005259
John McCall3b4294e2009-12-16 12:17:52 +00005260 if (ULE->requiresADL()) {
5261 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5262 E = ULE->decls_end(); I != E; ++I) {
5263 assert(!(*I)->getDeclContext()->isRecord());
5264 assert(isa<UsingShadowDecl>(*I) ||
5265 !(*I)->getDeclContext()->isFunctionOrMethod());
5266 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00005267 }
5268 }
5269#endif
5270
John McCall3b4294e2009-12-16 12:17:52 +00005271 // It would be nice to avoid this copy.
5272 TemplateArgumentListInfo TABuffer;
5273 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5274 if (ULE->hasExplicitTemplateArgs()) {
5275 ULE->copyTemplateArgumentsInto(TABuffer);
5276 ExplicitTemplateArgs = &TABuffer;
5277 }
5278
5279 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5280 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00005281 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00005282 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005283 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00005284
John McCall3b4294e2009-12-16 12:17:52 +00005285 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00005286 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5287 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005288 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005289 CandidateSet,
5290 PartialOverloading);
5291}
John McCall578b69b2009-12-16 08:11:27 +00005292
John McCall3b4294e2009-12-16 12:17:52 +00005293static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5294 Expr **Args, unsigned NumArgs) {
5295 Fn->Destroy(SemaRef.Context);
5296 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5297 Args[Arg]->Destroy(SemaRef.Context);
5298 return SemaRef.ExprError();
5299}
5300
John McCall578b69b2009-12-16 08:11:27 +00005301/// Attempts to recover from a call where no functions were found.
5302///
5303/// Returns true if new candidates were found.
John McCall3b4294e2009-12-16 12:17:52 +00005304static Sema::OwningExprResult
5305BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn,
5306 UnresolvedLookupExpr *ULE,
5307 SourceLocation LParenLoc,
5308 Expr **Args, unsigned NumArgs,
5309 SourceLocation *CommaLocs,
5310 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00005311
5312 CXXScopeSpec SS;
5313 if (ULE->getQualifier()) {
5314 SS.setScopeRep(ULE->getQualifier());
5315 SS.setRange(ULE->getQualifierRange());
5316 }
5317
John McCall3b4294e2009-12-16 12:17:52 +00005318 TemplateArgumentListInfo TABuffer;
5319 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5320 if (ULE->hasExplicitTemplateArgs()) {
5321 ULE->copyTemplateArgumentsInto(TABuffer);
5322 ExplicitTemplateArgs = &TABuffer;
5323 }
5324
John McCall578b69b2009-12-16 08:11:27 +00005325 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5326 Sema::LookupOrdinaryName);
Douglas Gregorbb092ba2009-12-31 05:20:13 +00005327 if (SemaRef.DiagnoseEmptyLookup(/*Scope=*/0, SS, R))
John McCall3b4294e2009-12-16 12:17:52 +00005328 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCall578b69b2009-12-16 08:11:27 +00005329
John McCall3b4294e2009-12-16 12:17:52 +00005330 assert(!R.empty() && "lookup results empty despite recovery");
5331
5332 // Build an implicit member call if appropriate. Just drop the
5333 // casts and such from the call, we don't really care.
5334 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5335 if ((*R.begin())->isCXXClassMember())
5336 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5337 else if (ExplicitTemplateArgs)
5338 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5339 else
5340 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5341
5342 if (NewFn.isInvalid())
5343 return Destroy(SemaRef, Fn, Args, NumArgs);
5344
5345 Fn->Destroy(SemaRef.Context);
5346
5347 // This shouldn't cause an infinite loop because we're giving it
5348 // an expression with non-empty lookup results, which should never
5349 // end up here.
5350 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5351 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5352 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00005353}
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005354
Douglas Gregorf6b89692008-11-26 05:54:23 +00005355/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00005356/// (which eventually refers to the declaration Func) and the call
5357/// arguments Args/NumArgs, attempt to resolve the function call down
5358/// to a specific function. If overload resolution succeeds, returns
5359/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00005360/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00005361/// arguments and Fn, and returns NULL.
John McCall3b4294e2009-12-16 12:17:52 +00005362Sema::OwningExprResult
5363Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE,
5364 SourceLocation LParenLoc,
5365 Expr **Args, unsigned NumArgs,
5366 SourceLocation *CommaLocs,
5367 SourceLocation RParenLoc) {
5368#ifndef NDEBUG
5369 if (ULE->requiresADL()) {
5370 // To do ADL, we must have found an unqualified name.
5371 assert(!ULE->getQualifier() && "qualified name with ADL");
5372
5373 // We don't perform ADL for implicit declarations of builtins.
5374 // Verify that this was correctly set up.
5375 FunctionDecl *F;
5376 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5377 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5378 F->getBuiltinID() && F->isImplicit())
5379 assert(0 && "performing ADL for builtin");
5380
5381 // We don't perform ADL in C.
5382 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5383 }
5384#endif
5385
John McCall5769d612010-02-08 23:07:23 +00005386 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00005387
John McCall3b4294e2009-12-16 12:17:52 +00005388 // Add the functions denoted by the callee to the set of candidate
5389 // functions, including those from argument-dependent lookup.
5390 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00005391
5392 // If we found nothing, try to recover.
5393 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5394 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00005395 if (CandidateSet.empty())
5396 return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs,
5397 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00005398
Douglas Gregorf6b89692008-11-26 05:54:23 +00005399 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005400 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00005401 case OR_Success: {
5402 FunctionDecl *FDecl = Best->Function;
John McCall9aa472c2010-03-19 07:35:19 +00005403 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall6bb80172010-03-30 21:47:33 +00005404 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall3b4294e2009-12-16 12:17:52 +00005405 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5406 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00005407
5408 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00005409 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00005410 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00005411 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005412 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00005413 break;
5414
5415 case OR_Ambiguous:
5416 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00005417 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005418 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00005419 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005420
5421 case OR_Deleted:
5422 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5423 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00005424 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005425 << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005426 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005427 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00005428 }
5429
5430 // Overload resolution failed. Destroy all of the subexpressions and
5431 // return NULL.
5432 Fn->Destroy(Context);
5433 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5434 Args[Arg]->Destroy(Context);
John McCall3b4294e2009-12-16 12:17:52 +00005435 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00005436}
5437
John McCall6e266892010-01-26 03:27:55 +00005438static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00005439 return Functions.size() > 1 ||
5440 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5441}
5442
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005443/// \brief Create a unary operation that may resolve to an overloaded
5444/// operator.
5445///
5446/// \param OpLoc The location of the operator itself (e.g., '*').
5447///
5448/// \param OpcIn The UnaryOperator::Opcode that describes this
5449/// operator.
5450///
5451/// \param Functions The set of non-member functions that will be
5452/// considered by overload resolution. The caller needs to build this
5453/// set based on the context using, e.g.,
5454/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5455/// set should not contain any member functions; those will be added
5456/// by CreateOverloadedUnaryOp().
5457///
5458/// \param input The input argument.
John McCall6e266892010-01-26 03:27:55 +00005459Sema::OwningExprResult
5460Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
5461 const UnresolvedSetImpl &Fns,
5462 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005463 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5464 Expr *Input = (Expr *)input.get();
5465
5466 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5467 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5468 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5469
5470 Expr *Args[2] = { Input, 0 };
5471 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00005472
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005473 // For post-increment and post-decrement, add the implicit '0' as
5474 // the second argument, so that we know this is a post-increment or
5475 // post-decrement.
5476 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5477 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00005478 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005479 SourceLocation());
5480 NumArgs = 2;
5481 }
5482
5483 if (Input->isTypeDependent()) {
John McCallc373d482010-01-27 01:50:18 +00005484 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00005485 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00005486 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00005487 0, SourceRange(), OpName, OpLoc,
John McCall6e266892010-01-26 03:27:55 +00005488 /*ADL*/ true, IsOverloaded(Fns));
5489 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump1eb44332009-09-09 15:08:12 +00005490
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005491 input.release();
5492 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5493 &Args[0], NumArgs,
5494 Context.DependentTy,
5495 OpLoc));
5496 }
5497
5498 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00005499 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005500
5501 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00005502 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005503
5504 // Add operator candidates that are member functions.
5505 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5506
John McCall6e266892010-01-26 03:27:55 +00005507 // Add candidates from ADL.
5508 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00005509 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00005510 /*ExplicitTemplateArgs*/ 0,
5511 CandidateSet);
5512
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005513 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00005514 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005515
5516 // Perform overload resolution.
5517 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005518 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005519 case OR_Success: {
5520 // We found a built-in operator or an overloaded operator.
5521 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00005522
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005523 if (FnDecl) {
5524 // We matched an overloaded operator. Build a call to that
5525 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00005526
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005527 // Convert the arguments.
5528 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00005529 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00005530
John McCall6bb80172010-03-30 21:47:33 +00005531 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
5532 Best->FoundDecl, Method))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005533 return ExprError();
5534 } else {
5535 // Convert the arguments.
Douglas Gregore1a5c172009-12-23 17:40:29 +00005536 OwningExprResult InputInit
5537 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005538 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00005539 SourceLocation(),
5540 move(input));
5541 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005542 return ExprError();
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005543
Douglas Gregore1a5c172009-12-23 17:40:29 +00005544 input = move(InputInit);
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005545 Input = (Expr *)input.get();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005546 }
5547
5548 // Determine the result type
Anders Carlsson26a2a072009-10-13 21:19:37 +00005549 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00005550
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005551 // Build the actual expression node.
5552 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5553 SourceLocation());
5554 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00005555
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005556 input.release();
Eli Friedman4c3b8962009-11-18 03:58:17 +00005557 Args[0] = Input;
Anders Carlsson26a2a072009-10-13 21:19:37 +00005558 ExprOwningPtr<CallExpr> TheCall(this,
5559 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman4c3b8962009-11-18 03:58:17 +00005560 Args, NumArgs, ResultTy, OpLoc));
Anders Carlsson26a2a072009-10-13 21:19:37 +00005561
5562 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5563 FnDecl))
5564 return ExprError();
5565
5566 return MaybeBindToTemporary(TheCall.release());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005567 } else {
5568 // We matched a built-in operator. Convert the arguments, then
5569 // break out so that we will build the appropriate built-in
5570 // operator node.
5571 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005572 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005573 return ExprError();
5574
5575 break;
5576 }
5577 }
5578
5579 case OR_No_Viable_Function:
5580 // No viable function; fall through to handling this as a
5581 // built-in operator, which will produce an error message for us.
5582 break;
5583
5584 case OR_Ambiguous:
5585 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5586 << UnaryOperator::getOpcodeStr(Opc)
5587 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005588 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005589 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005590 return ExprError();
5591
5592 case OR_Deleted:
5593 Diag(OpLoc, diag::err_ovl_deleted_oper)
5594 << Best->Function->isDeleted()
5595 << UnaryOperator::getOpcodeStr(Opc)
5596 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005597 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005598 return ExprError();
5599 }
5600
5601 // Either we found no viable overloaded operator or we matched a
5602 // built-in operator. In either case, fall through to trying to
5603 // build a built-in operation.
5604 input.release();
5605 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5606}
5607
Douglas Gregor063daf62009-03-13 18:40:31 +00005608/// \brief Create a binary operation that may resolve to an overloaded
5609/// operator.
5610///
5611/// \param OpLoc The location of the operator itself (e.g., '+').
5612///
5613/// \param OpcIn The BinaryOperator::Opcode that describes this
5614/// operator.
5615///
5616/// \param Functions The set of non-member functions that will be
5617/// considered by overload resolution. The caller needs to build this
5618/// set based on the context using, e.g.,
5619/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5620/// set should not contain any member functions; those will be added
5621/// by CreateOverloadedBinOp().
5622///
5623/// \param LHS Left-hand argument.
5624/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00005625Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00005626Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005627 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00005628 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00005629 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00005630 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005631 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00005632
5633 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5634 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5635 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5636
5637 // If either side is type-dependent, create an appropriate dependent
5638 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005639 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00005640 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005641 // If there are no functions to store, just build a dependent
5642 // BinaryOperator or CompoundAssignment.
5643 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5644 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5645 Context.DependentTy, OpLoc));
5646
5647 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5648 Context.DependentTy,
5649 Context.DependentTy,
5650 Context.DependentTy,
5651 OpLoc));
5652 }
John McCall6e266892010-01-26 03:27:55 +00005653
5654 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00005655 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00005656 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00005657 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00005658 0, SourceRange(), OpName, OpLoc,
John McCall6e266892010-01-26 03:27:55 +00005659 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump1eb44332009-09-09 15:08:12 +00005660
John McCall6e266892010-01-26 03:27:55 +00005661 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00005662 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00005663 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00005664 Context.DependentTy,
5665 OpLoc));
5666 }
5667
5668 // If this is the .* operator, which is not overloadable, just
5669 // create a built-in binary operator.
5670 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005671 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005672
Sebastian Redl275c2b42009-11-18 23:10:33 +00005673 // If this is the assignment operator, we only perform overload resolution
5674 // if the left-hand side is a class or enumeration type. This is actually
5675 // a hack. The standard requires that we do overload resolution between the
5676 // various built-in candidates, but as DR507 points out, this can lead to
5677 // problems. So we do it this way, which pretty much follows what GCC does.
5678 // Note that we go the traditional code path for compound assignment forms.
5679 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005680 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005681
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005682 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00005683 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00005684
5685 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00005686 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00005687
5688 // Add operator candidates that are member functions.
5689 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5690
John McCall6e266892010-01-26 03:27:55 +00005691 // Add candidates from ADL.
5692 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
5693 Args, 2,
5694 /*ExplicitTemplateArgs*/ 0,
5695 CandidateSet);
5696
Douglas Gregor063daf62009-03-13 18:40:31 +00005697 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00005698 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00005699
5700 // Perform overload resolution.
5701 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005702 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005703 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00005704 // We found a built-in operator or an overloaded operator.
5705 FunctionDecl *FnDecl = Best->Function;
5706
5707 if (FnDecl) {
5708 // We matched an overloaded operator. Build a call to that
5709 // operator.
5710
5711 // Convert the arguments.
5712 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00005713 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00005714 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00005715
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005716 OwningExprResult Arg1
5717 = PerformCopyInitialization(
5718 InitializedEntity::InitializeParameter(
5719 FnDecl->getParamDecl(0)),
5720 SourceLocation(),
5721 Owned(Args[1]));
5722 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00005723 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005724
Douglas Gregor5fccd362010-03-03 23:55:11 +00005725 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00005726 Best->FoundDecl, Method))
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005727 return ExprError();
5728
5729 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00005730 } else {
5731 // Convert the arguments.
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005732 OwningExprResult Arg0
5733 = PerformCopyInitialization(
5734 InitializedEntity::InitializeParameter(
5735 FnDecl->getParamDecl(0)),
5736 SourceLocation(),
5737 Owned(Args[0]));
5738 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00005739 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005740
5741 OwningExprResult Arg1
5742 = PerformCopyInitialization(
5743 InitializedEntity::InitializeParameter(
5744 FnDecl->getParamDecl(1)),
5745 SourceLocation(),
5746 Owned(Args[1]));
5747 if (Arg1.isInvalid())
5748 return ExprError();
5749 Args[0] = LHS = Arg0.takeAs<Expr>();
5750 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00005751 }
5752
5753 // Determine the result type
5754 QualType ResultTy
John McCall183700f2009-09-21 23:43:11 +00005755 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor063daf62009-03-13 18:40:31 +00005756 ResultTy = ResultTy.getNonReferenceType();
5757
5758 // Build the actual expression node.
5759 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00005760 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00005761 UsualUnaryConversions(FnExpr);
5762
Anders Carlsson15ea3782009-10-13 22:43:21 +00005763 ExprOwningPtr<CXXOperatorCallExpr>
5764 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5765 Args, 2, ResultTy,
5766 OpLoc));
5767
5768 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5769 FnDecl))
5770 return ExprError();
5771
5772 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor063daf62009-03-13 18:40:31 +00005773 } else {
5774 // We matched a built-in operator. Convert the arguments, then
5775 // break out so that we will build the appropriate built-in
5776 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005777 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005778 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005779 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00005780 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00005781 return ExprError();
5782
5783 break;
5784 }
5785 }
5786
Douglas Gregor33074752009-09-30 21:46:01 +00005787 case OR_No_Viable_Function: {
5788 // C++ [over.match.oper]p9:
5789 // If the operator is the operator , [...] and there are no
5790 // viable functions, then the operator is assumed to be the
5791 // built-in operator and interpreted according to clause 5.
5792 if (Opc == BinaryOperator::Comma)
5793 break;
5794
Sebastian Redl8593c782009-05-21 11:50:50 +00005795 // For class as left operand for assignment or compound assigment operator
5796 // do not fall through to handling in built-in, but report that no overloaded
5797 // assignment operator found
Douglas Gregor33074752009-09-30 21:46:01 +00005798 OwningExprResult Result = ExprError();
5799 if (Args[0]->getType()->isRecordType() &&
5800 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00005801 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5802 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005803 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00005804 } else {
5805 // No viable function; try to create a built-in operation, which will
5806 // produce an error. Then, show the non-viable candidates.
5807 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00005808 }
Douglas Gregor33074752009-09-30 21:46:01 +00005809 assert(Result.isInvalid() &&
5810 "C++ binary operator overloading is missing candidates!");
5811 if (Result.isInvalid())
John McCallcbce6062010-01-12 07:18:19 +00005812 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005813 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00005814 return move(Result);
5815 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005816
5817 case OR_Ambiguous:
5818 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5819 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005820 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005821 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005822 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00005823 return ExprError();
5824
5825 case OR_Deleted:
5826 Diag(OpLoc, diag::err_ovl_deleted_oper)
5827 << Best->Function->isDeleted()
5828 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005829 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005830 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00005831 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00005832 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005833
Douglas Gregor33074752009-09-30 21:46:01 +00005834 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005835 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005836}
5837
Sebastian Redlf322ed62009-10-29 20:17:01 +00005838Action::OwningExprResult
5839Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5840 SourceLocation RLoc,
5841 ExprArg Base, ExprArg Idx) {
5842 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5843 static_cast<Expr*>(Idx.get()) };
5844 DeclarationName OpName =
5845 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5846
5847 // If either side is type-dependent, create an appropriate dependent
5848 // expression.
5849 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5850
John McCallc373d482010-01-27 01:50:18 +00005851 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00005852 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00005853 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00005854 0, SourceRange(), OpName, LLoc,
John McCall7453ed42009-11-22 00:44:51 +00005855 /*ADL*/ true, /*Overloaded*/ false);
John McCallf7a1a742009-11-24 19:00:30 +00005856 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00005857
5858 Base.release();
5859 Idx.release();
5860 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5861 Args, 2,
5862 Context.DependentTy,
5863 RLoc));
5864 }
5865
5866 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00005867 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00005868
5869 // Subscript can only be overloaded as a member function.
5870
5871 // Add operator candidates that are member functions.
5872 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5873
5874 // Add builtin operator candidates.
5875 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5876
5877 // Perform overload resolution.
5878 OverloadCandidateSet::iterator Best;
5879 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5880 case OR_Success: {
5881 // We found a built-in operator or an overloaded operator.
5882 FunctionDecl *FnDecl = Best->Function;
5883
5884 if (FnDecl) {
5885 // We matched an overloaded operator. Build a call to that
5886 // operator.
5887
John McCall9aa472c2010-03-19 07:35:19 +00005888 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallc373d482010-01-27 01:50:18 +00005889
Sebastian Redlf322ed62009-10-29 20:17:01 +00005890 // Convert the arguments.
5891 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregor5fccd362010-03-03 23:55:11 +00005892 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00005893 Best->FoundDecl, Method))
Sebastian Redlf322ed62009-10-29 20:17:01 +00005894 return ExprError();
5895
Anders Carlsson38f88ab2010-01-29 18:37:50 +00005896 // Convert the arguments.
5897 OwningExprResult InputInit
5898 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
5899 FnDecl->getParamDecl(0)),
5900 SourceLocation(),
5901 Owned(Args[1]));
5902 if (InputInit.isInvalid())
5903 return ExprError();
5904
5905 Args[1] = InputInit.takeAs<Expr>();
5906
Sebastian Redlf322ed62009-10-29 20:17:01 +00005907 // Determine the result type
5908 QualType ResultTy
5909 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5910 ResultTy = ResultTy.getNonReferenceType();
5911
5912 // Build the actual expression node.
5913 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5914 LLoc);
5915 UsualUnaryConversions(FnExpr);
5916
5917 Base.release();
5918 Idx.release();
5919 ExprOwningPtr<CXXOperatorCallExpr>
5920 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5921 FnExpr, Args, 2,
5922 ResultTy, RLoc));
5923
5924 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5925 FnDecl))
5926 return ExprError();
5927
5928 return MaybeBindToTemporary(TheCall.release());
5929 } else {
5930 // We matched a built-in operator. Convert the arguments, then
5931 // break out so that we will build the appropriate built-in
5932 // operator node.
5933 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005934 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00005935 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00005936 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00005937 return ExprError();
5938
5939 break;
5940 }
5941 }
5942
5943 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00005944 if (CandidateSet.empty())
5945 Diag(LLoc, diag::err_ovl_no_oper)
5946 << Args[0]->getType() << /*subscript*/ 0
5947 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5948 else
5949 Diag(LLoc, diag::err_ovl_no_viable_subscript)
5950 << Args[0]->getType()
5951 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005952 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall1eb3e102010-01-07 02:04:15 +00005953 "[]", LLoc);
5954 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00005955 }
5956
5957 case OR_Ambiguous:
5958 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5959 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005960 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redlf322ed62009-10-29 20:17:01 +00005961 "[]", LLoc);
5962 return ExprError();
5963
5964 case OR_Deleted:
5965 Diag(LLoc, diag::err_ovl_deleted_oper)
5966 << Best->Function->isDeleted() << "[]"
5967 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005968 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall81201622010-01-08 04:41:39 +00005969 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00005970 return ExprError();
5971 }
5972
5973 // We matched a built-in operator; build it.
5974 Base.release();
5975 Idx.release();
5976 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5977 Owned(Args[1]), RLoc);
5978}
5979
Douglas Gregor88a35142008-12-22 05:46:06 +00005980/// BuildCallToMemberFunction - Build a call to a member
5981/// function. MemExpr is the expression that refers to the member
5982/// function (and includes the object parameter), Args/NumArgs are the
5983/// arguments to the function call (not including the object
5984/// parameter). The caller needs to validate that the member
5985/// expression refers to a member function or an overloaded member
5986/// function.
John McCallaa81e162009-12-01 22:10:20 +00005987Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00005988Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5989 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00005990 unsigned NumArgs, SourceLocation *CommaLocs,
5991 SourceLocation RParenLoc) {
5992 // Dig out the member expression. This holds both the object
5993 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00005994 Expr *NakedMemExpr = MemExprE->IgnoreParens();
5995
John McCall129e2df2009-11-30 22:42:35 +00005996 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00005997 CXXMethodDecl *Method = 0;
John McCall6bb80172010-03-30 21:47:33 +00005998 NamedDecl *FoundDecl = 0;
Douglas Gregor5fccd362010-03-03 23:55:11 +00005999 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00006000 if (isa<MemberExpr>(NakedMemExpr)) {
6001 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00006002 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00006003 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00006004 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00006005 } else {
6006 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00006007 Qualifier = UnresExpr->getQualifier();
6008
John McCall701c89e2009-12-03 04:06:58 +00006009 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00006010
Douglas Gregor88a35142008-12-22 05:46:06 +00006011 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00006012 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00006013
John McCallaa81e162009-12-01 22:10:20 +00006014 // FIXME: avoid copy.
6015 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6016 if (UnresExpr->hasExplicitTemplateArgs()) {
6017 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6018 TemplateArgs = &TemplateArgsBuffer;
6019 }
6020
John McCall129e2df2009-11-30 22:42:35 +00006021 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6022 E = UnresExpr->decls_end(); I != E; ++I) {
6023
John McCall701c89e2009-12-03 04:06:58 +00006024 NamedDecl *Func = *I;
6025 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6026 if (isa<UsingShadowDecl>(Func))
6027 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6028
John McCall129e2df2009-11-30 22:42:35 +00006029 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006030 // If explicit template arguments were provided, we can't call a
6031 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00006032 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006033 continue;
6034
John McCall9aa472c2010-03-19 07:35:19 +00006035 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCall86820f52010-01-26 01:37:31 +00006036 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00006037 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00006038 } else {
John McCall129e2df2009-11-30 22:42:35 +00006039 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00006040 I.getPair(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00006041 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00006042 CandidateSet,
6043 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00006044 }
Douglas Gregordec06662009-08-21 18:42:58 +00006045 }
Mike Stump1eb44332009-09-09 15:08:12 +00006046
John McCall129e2df2009-11-30 22:42:35 +00006047 DeclarationName DeclName = UnresExpr->getMemberName();
6048
Douglas Gregor88a35142008-12-22 05:46:06 +00006049 OverloadCandidateSet::iterator Best;
John McCall129e2df2009-11-30 22:42:35 +00006050 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00006051 case OR_Success:
6052 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00006053 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00006054 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Douglas Gregor88a35142008-12-22 05:46:06 +00006055 break;
6056
6057 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00006058 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00006059 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00006060 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006061 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00006062 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006063 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006064
6065 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00006066 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00006067 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006068 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00006069 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006070 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006071
6072 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00006073 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006074 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00006075 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006076 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006077 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006078 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006079 }
6080
John McCall6bb80172010-03-30 21:47:33 +00006081 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00006082
John McCallaa81e162009-12-01 22:10:20 +00006083 // If overload resolution picked a static member, build a
6084 // non-member call based on that function.
6085 if (Method->isStatic()) {
6086 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6087 Args, NumArgs, RParenLoc);
6088 }
6089
John McCall129e2df2009-11-30 22:42:35 +00006090 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00006091 }
6092
6093 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00006094 ExprOwningPtr<CXXMemberCallExpr>
John McCallaa81e162009-12-01 22:10:20 +00006095 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00006096 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00006097 Method->getResultType().getNonReferenceType(),
6098 RParenLoc));
6099
Anders Carlssoneed3e692009-10-10 00:06:20 +00006100 // Check for a valid return type.
6101 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6102 TheCall.get(), Method))
John McCallaa81e162009-12-01 22:10:20 +00006103 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00006104
Douglas Gregor88a35142008-12-22 05:46:06 +00006105 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00006106 // We only need to do this if there was actually an overload; otherwise
6107 // it was done at lookup.
John McCallaa81e162009-12-01 22:10:20 +00006108 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00006109 if (!Method->isStatic() &&
John McCall6bb80172010-03-30 21:47:33 +00006110 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
6111 FoundDecl, Method))
John McCallaa81e162009-12-01 22:10:20 +00006112 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006113 MemExpr->setBase(ObjectArg);
6114
6115 // Convert the rest of the arguments
Douglas Gregor72564e72009-02-26 23:50:07 +00006116 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00006117 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00006118 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00006119 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006120
Anders Carlssond406bf02009-08-16 01:56:34 +00006121 if (CheckFunctionCall(Method, TheCall.get()))
John McCallaa81e162009-12-01 22:10:20 +00006122 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00006123
John McCallaa81e162009-12-01 22:10:20 +00006124 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor88a35142008-12-22 05:46:06 +00006125}
6126
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006127/// BuildCallToObjectOfClassType - Build a call to an object of class
6128/// type (C++ [over.call.object]), which can end up invoking an
6129/// overloaded function call operator (@c operator()) or performing a
6130/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00006131Sema::ExprResult
6132Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00006133 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006134 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00006135 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006136 SourceLocation RParenLoc) {
6137 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00006138 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006139
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006140 // C++ [over.call.object]p1:
6141 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00006142 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006143 // candidate functions includes at least the function call
6144 // operators of T. The function call operators of T are obtained by
6145 // ordinary lookup of the name operator() in the context of
6146 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00006147 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00006148 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00006149
6150 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006151 PDiag(diag::err_incomplete_object_call)
Douglas Gregor593564b2009-11-15 07:48:03 +00006152 << Object->getSourceRange()))
6153 return true;
6154
John McCalla24dc2e2009-11-17 02:14:36 +00006155 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6156 LookupQualifiedName(R, Record->getDecl());
6157 R.suppressDiagnostics();
6158
Douglas Gregor593564b2009-11-15 07:48:03 +00006159 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00006160 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00006161 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCall86820f52010-01-26 01:37:31 +00006162 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006163 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00006164 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00006165
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006166 // C++ [over.call.object]p2:
6167 // In addition, for each conversion function declared in T of the
6168 // form
6169 //
6170 // operator conversion-type-id () cv-qualifier;
6171 //
6172 // where cv-qualifier is the same cv-qualification as, or a
6173 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00006174 // denotes the type "pointer to function of (P1,...,Pn) returning
6175 // R", or the type "reference to pointer to function of
6176 // (P1,...,Pn) returning R", or the type "reference to function
6177 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006178 // is also considered as a candidate function. Similarly,
6179 // surrogate call functions are added to the set of candidate
6180 // functions for each conversion function declared in an
6181 // accessible base class provided the function is not hidden
6182 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00006183 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00006184 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00006185 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00006186 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00006187 NamedDecl *D = *I;
6188 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6189 if (isa<UsingShadowDecl>(D))
6190 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6191
Douglas Gregor4a27d702009-10-21 06:18:39 +00006192 // Skip over templated conversion functions; they aren't
6193 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00006194 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00006195 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006196
John McCall701c89e2009-12-03 04:06:58 +00006197 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00006198
Douglas Gregor4a27d702009-10-21 06:18:39 +00006199 // Strip the reference type (if any) and then the pointer type (if
6200 // any) to get down to what might be a function type.
6201 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6202 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6203 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006204
Douglas Gregor4a27d702009-10-21 06:18:39 +00006205 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall9aa472c2010-03-19 07:35:19 +00006206 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00006207 Object->getType(), Args, NumArgs,
6208 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006209 }
Mike Stump1eb44332009-09-09 15:08:12 +00006210
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006211 // Perform overload resolution.
6212 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006213 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006214 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006215 // Overload resolution succeeded; we'll build the appropriate call
6216 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006217 break;
6218
6219 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00006220 if (CandidateSet.empty())
6221 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6222 << Object->getType() << /*call*/ 1
6223 << Object->getSourceRange();
6224 else
6225 Diag(Object->getSourceRange().getBegin(),
6226 diag::err_ovl_no_viable_object_call)
6227 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006228 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006229 break;
6230
6231 case OR_Ambiguous:
6232 Diag(Object->getSourceRange().getBegin(),
6233 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00006234 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006235 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006236 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006237
6238 case OR_Deleted:
6239 Diag(Object->getSourceRange().getBegin(),
6240 diag::err_ovl_deleted_object_call)
6241 << Best->Function->isDeleted()
6242 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006243 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006244 break;
Mike Stump1eb44332009-09-09 15:08:12 +00006245 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006246
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006247 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006248 // We had an error; delete all of the subexpressions and return
6249 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00006250 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006251 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00006252 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006253 return true;
6254 }
6255
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006256 if (Best->Function == 0) {
6257 // Since there is no function declaration, this is one of the
6258 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00006259 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006260 = cast<CXXConversionDecl>(
6261 Best->Conversions[0].UserDefined.ConversionFunction);
6262
John McCall9aa472c2010-03-19 07:35:19 +00006263 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall41d89032010-01-28 01:54:34 +00006264
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006265 // We selected one of the surrogate functions that converts the
6266 // object parameter to a function pointer. Perform the conversion
6267 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00006268
6269 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00006270 // and then call it.
John McCall6bb80172010-03-30 21:47:33 +00006271 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
6272 Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00006273
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00006274 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00006275 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
6276 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006277 }
6278
John McCall9aa472c2010-03-19 07:35:19 +00006279 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall41d89032010-01-28 01:54:34 +00006280
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006281 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6282 // that calls this method, using Object for the implicit object
6283 // parameter and passing along the remaining arguments.
6284 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00006285 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006286
6287 unsigned NumArgsInProto = Proto->getNumArgs();
6288 unsigned NumArgsToCheck = NumArgs;
6289
6290 // Build the full argument list for the method call (the
6291 // implicit object parameter is placed at the beginning of the
6292 // list).
6293 Expr **MethodArgs;
6294 if (NumArgs < NumArgsInProto) {
6295 NumArgsToCheck = NumArgsInProto;
6296 MethodArgs = new Expr*[NumArgsInProto + 1];
6297 } else {
6298 MethodArgs = new Expr*[NumArgs + 1];
6299 }
6300 MethodArgs[0] = Object;
6301 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6302 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00006303
6304 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00006305 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006306 UsualUnaryConversions(NewFn);
6307
6308 // Once we've built TheCall, all of the expressions are properly
6309 // owned.
6310 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00006311 ExprOwningPtr<CXXOperatorCallExpr>
6312 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00006313 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00006314 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006315 delete [] MethodArgs;
6316
Anders Carlsson07d68f12009-10-13 21:49:31 +00006317 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6318 Method))
6319 return true;
6320
Douglas Gregor518fda12009-01-13 05:10:00 +00006321 // We may have default arguments. If so, we need to allocate more
6322 // slots in the call for them.
6323 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00006324 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00006325 else if (NumArgs > NumArgsInProto)
6326 NumArgsToCheck = NumArgsInProto;
6327
Chris Lattner312531a2009-04-12 08:11:20 +00006328 bool IsError = false;
6329
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006330 // Initialize the implicit object parameter.
Douglas Gregor5fccd362010-03-03 23:55:11 +00006331 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00006332 Best->FoundDecl, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006333 TheCall->setArg(0, Object);
6334
Chris Lattner312531a2009-04-12 08:11:20 +00006335
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006336 // Check the argument types.
6337 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006338 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00006339 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006340 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00006341
Douglas Gregor518fda12009-01-13 05:10:00 +00006342 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00006343
6344 OwningExprResult InputInit
6345 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6346 Method->getParamDecl(i)),
6347 SourceLocation(), Owned(Arg));
6348
6349 IsError |= InputInit.isInvalid();
6350 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00006351 } else {
Douglas Gregord47c47d2009-11-09 19:27:57 +00006352 OwningExprResult DefArg
6353 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6354 if (DefArg.isInvalid()) {
6355 IsError = true;
6356 break;
6357 }
6358
6359 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00006360 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006361
6362 TheCall->setArg(i + 1, Arg);
6363 }
6364
6365 // If this is a variadic call, handle args passed through "...".
6366 if (Proto->isVariadic()) {
6367 // Promote the arguments (C99 6.5.2.2p7).
6368 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6369 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00006370 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006371 TheCall->setArg(i + 1, Arg);
6372 }
6373 }
6374
Chris Lattner312531a2009-04-12 08:11:20 +00006375 if (IsError) return true;
6376
Anders Carlssond406bf02009-08-16 01:56:34 +00006377 if (CheckFunctionCall(Method, TheCall.get()))
6378 return true;
6379
Anders Carlssona303f9e2009-08-16 03:53:54 +00006380 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006381}
6382
Douglas Gregor8ba10742008-11-20 16:27:02 +00006383/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00006384/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00006385/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006386Sema::OwningExprResult
6387Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6388 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00006389 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00006390
John McCall5769d612010-02-08 23:07:23 +00006391 SourceLocation Loc = Base->getExprLoc();
6392
Douglas Gregor8ba10742008-11-20 16:27:02 +00006393 // C++ [over.ref]p1:
6394 //
6395 // [...] An expression x->m is interpreted as (x.operator->())->m
6396 // for a class object x of type T if T::operator->() exists and if
6397 // the operator is selected as the best match function by the
6398 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00006399 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00006400 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00006401 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006402
John McCall5769d612010-02-08 23:07:23 +00006403 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00006404 PDiag(diag::err_typecheck_incomplete_tag)
6405 << Base->getSourceRange()))
6406 return ExprError();
6407
John McCalla24dc2e2009-11-17 02:14:36 +00006408 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6409 LookupQualifiedName(R, BaseRecord->getDecl());
6410 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00006411
6412 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00006413 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00006414 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00006415 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00006416 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00006417
6418 // Perform overload resolution.
6419 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006420 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00006421 case OR_Success:
6422 // Overload resolution succeeded; we'll build the call below.
6423 break;
6424
6425 case OR_No_Viable_Function:
6426 if (CandidateSet.empty())
6427 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006428 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006429 else
6430 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006431 << "operator->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006432 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006433 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006434
6435 case OR_Ambiguous:
6436 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00006437 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006438 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006439 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006440
6441 case OR_Deleted:
6442 Diag(OpLoc, diag::err_ovl_deleted_oper)
6443 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00006444 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006445 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006446 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006447 }
6448
John McCall9aa472c2010-03-19 07:35:19 +00006449 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
6450
Douglas Gregor8ba10742008-11-20 16:27:02 +00006451 // Convert the object parameter.
6452 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00006453 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
6454 Best->FoundDecl, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006455 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00006456
6457 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006458 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006459
6460 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00006461 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6462 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00006463 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00006464
6465 QualType ResultTy = Method->getResultType().getNonReferenceType();
6466 ExprOwningPtr<CXXOperatorCallExpr>
6467 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6468 &Base, 1, ResultTy, OpLoc));
6469
6470 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6471 Method))
6472 return ExprError();
6473 return move(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00006474}
6475
Douglas Gregor904eed32008-11-10 20:40:00 +00006476/// FixOverloadedFunctionReference - E is an expression that refers to
6477/// a C++ overloaded function (possibly with some parentheses and
6478/// perhaps a '&' around it). We have resolved the overloaded function
6479/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00006480/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall6bb80172010-03-30 21:47:33 +00006481Expr *Sema::FixOverloadedFunctionReference(Expr *E, NamedDecl *Found,
6482 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006483 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00006484 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
6485 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00006486 if (SubExpr == PE->getSubExpr())
6487 return PE->Retain();
6488
6489 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6490 }
6491
6492 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00006493 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
6494 Found, Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00006495 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00006496 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00006497 "Implicit cast type cannot be determined from overload");
Douglas Gregor699ee522009-11-20 19:42:02 +00006498 if (SubExpr == ICE->getSubExpr())
6499 return ICE->Retain();
6500
6501 return new (Context) ImplicitCastExpr(ICE->getType(),
6502 ICE->getCastKind(),
6503 SubExpr,
6504 ICE->isLvalueCast());
6505 }
6506
6507 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006508 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00006509 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00006510 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6511 if (Method->isStatic()) {
6512 // Do nothing: static member functions aren't any different
6513 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00006514 } else {
John McCallf7a1a742009-11-24 19:00:30 +00006515 // Fix the sub expression, which really has to be an
6516 // UnresolvedLookupExpr holding an overloaded member function
6517 // or template.
John McCall6bb80172010-03-30 21:47:33 +00006518 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6519 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00006520 if (SubExpr == UnOp->getSubExpr())
6521 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00006522
John McCallba135432009-11-21 08:51:07 +00006523 assert(isa<DeclRefExpr>(SubExpr)
6524 && "fixed to something other than a decl ref");
6525 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6526 && "fixed to a member ref with no nested name qualifier");
6527
6528 // We have taken the address of a pointer to member
6529 // function. Perform the computation here so that we get the
6530 // appropriate pointer to member type.
6531 QualType ClassType
6532 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6533 QualType MemPtrType
6534 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6535
6536 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6537 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00006538 }
6539 }
John McCall6bb80172010-03-30 21:47:33 +00006540 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6541 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00006542 if (SubExpr == UnOp->getSubExpr())
6543 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00006544
Douglas Gregor699ee522009-11-20 19:42:02 +00006545 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6546 Context.getPointerType(SubExpr->getType()),
6547 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00006548 }
John McCallba135432009-11-21 08:51:07 +00006549
6550 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00006551 // FIXME: avoid copy.
6552 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00006553 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00006554 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6555 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00006556 }
6557
John McCallba135432009-11-21 08:51:07 +00006558 return DeclRefExpr::Create(Context,
6559 ULE->getQualifier(),
6560 ULE->getQualifierRange(),
6561 Fn,
6562 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00006563 Fn->getType(),
6564 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00006565 }
6566
John McCall129e2df2009-11-30 22:42:35 +00006567 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00006568 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00006569 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6570 if (MemExpr->hasExplicitTemplateArgs()) {
6571 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6572 TemplateArgs = &TemplateArgsBuffer;
6573 }
John McCalld5532b62009-11-23 01:53:49 +00006574
John McCallaa81e162009-12-01 22:10:20 +00006575 Expr *Base;
6576
6577 // If we're filling in
6578 if (MemExpr->isImplicitAccess()) {
6579 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6580 return DeclRefExpr::Create(Context,
6581 MemExpr->getQualifier(),
6582 MemExpr->getQualifierRange(),
6583 Fn,
6584 MemExpr->getMemberLoc(),
6585 Fn->getType(),
6586 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00006587 } else {
6588 SourceLocation Loc = MemExpr->getMemberLoc();
6589 if (MemExpr->getQualifier())
6590 Loc = MemExpr->getQualifierRange().getBegin();
6591 Base = new (Context) CXXThisExpr(Loc,
6592 MemExpr->getBaseType(),
6593 /*isImplicit=*/true);
6594 }
John McCallaa81e162009-12-01 22:10:20 +00006595 } else
6596 Base = MemExpr->getBase()->Retain();
6597
6598 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00006599 MemExpr->isArrow(),
6600 MemExpr->getQualifier(),
6601 MemExpr->getQualifierRange(),
6602 Fn,
John McCall6bb80172010-03-30 21:47:33 +00006603 Found,
John McCalld5532b62009-11-23 01:53:49 +00006604 MemExpr->getMemberLoc(),
John McCallaa81e162009-12-01 22:10:20 +00006605 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00006606 Fn->getType());
6607 }
6608
Douglas Gregor699ee522009-11-20 19:42:02 +00006609 assert(false && "Invalid reference to overloaded function");
6610 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00006611}
6612
Douglas Gregor20093b42009-12-09 23:02:17 +00006613Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCall6bb80172010-03-30 21:47:33 +00006614 NamedDecl *Found,
Douglas Gregor20093b42009-12-09 23:02:17 +00006615 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +00006616 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +00006617}
6618
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006619} // end namespace clang