blob: 58d7d6750855ab5f77fe4473593a57ead1049dc1 [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
Mike Stump1eb44332009-09-09 15:08:12 +0000570 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000571 // An lvalue (3.10) of a non-function, non-array type T can be
572 // converted to an rvalue.
573 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000574 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000575 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000576 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000577 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000578
579 // If T is a non-class type, the type of the rvalue is the
580 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000581 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
582 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000583 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000584 } else if (FromType->isArrayType()) {
585 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000586 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000587
588 // An lvalue or rvalue of type "array of N T" or "array of unknown
589 // bound of T" can be converted to an rvalue of type "pointer to
590 // T" (C++ 4.2p1).
591 FromType = Context.getArrayDecayedType(FromType);
592
593 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
594 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +0000595 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000596
597 // For the purpose of ranking in overload resolution
598 // (13.3.3.1.1), this conversion is considered an
599 // array-to-pointer conversion followed by a qualification
600 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000601 SCS.Second = ICK_Identity;
602 SCS.Third = ICK_Qualification;
Douglas Gregorad323a82010-01-27 03:51:04 +0000603 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000604 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000605 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000606 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
607 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000608 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000609
610 // An lvalue of function type T can be converted to an rvalue of
611 // type "pointer to T." The result is a pointer to the
612 // function. (C++ 4.3p1).
613 FromType = Context.getPointerType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000614 } else if (FunctionDecl *Fn
Douglas Gregor43c79c22009-12-09 00:47:37 +0000615 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000616 // Address of overloaded function (C++ [over.over]).
Douglas Gregor904eed32008-11-10 20:40:00 +0000617 SCS.First = ICK_Function_To_Pointer;
618
619 // We were able to resolve the address of the overloaded function,
620 // so we can convert to the type of that function.
621 FromType = Fn->getType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000622 if (ToType->isLValueReferenceType())
623 FromType = Context.getLValueReferenceType(FromType);
624 else if (ToType->isRValueReferenceType())
625 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000626 else if (ToType->isMemberPointerType()) {
627 // Resolve address only succeeds if both sides are member pointers,
628 // but it doesn't have to be the same class. See DR 247.
629 // Note that this means that the type of &Derived::fn can be
630 // Ret (Base::*)(Args) if the fn overload actually found is from the
631 // base class, even if it was brought into the derived class via a
632 // using declaration. The standard isn't clear on this issue at all.
633 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
634 FromType = Context.getMemberPointerType(FromType,
635 Context.getTypeDeclType(M->getParent()).getTypePtr());
636 } else
Douglas Gregor904eed32008-11-10 20:40:00 +0000637 FromType = Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000638 } else {
639 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000640 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000641 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000642 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000643
644 // The second conversion can be an integral promotion, floating
645 // point promotion, integral conversion, floating point conversion,
646 // floating-integral conversion, pointer conversion,
647 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000648 // For overloading in C, this can also be a "compatible-type"
649 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000650 bool IncompatibleObjC = false;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000651 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000652 // The unqualified versions of the types are the same: there's no
653 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000654 SCS.Second = ICK_Identity;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000655 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000656 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000657 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000658 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000659 } else if (IsFloatingPointPromotion(FromType, ToType)) {
660 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000661 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000662 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000663 } else if (IsComplexPromotion(FromType, ToType)) {
664 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000665 SCS.Second = ICK_Complex_Promotion;
666 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000667 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000668 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000669 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000670 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000671 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000672 } else if (FromType->isComplexType() && ToType->isComplexType()) {
673 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000674 SCS.Second = ICK_Complex_Conversion;
675 FromType = ToType.getUnqualifiedType();
Chandler Carruth23a370f2010-02-25 07:20:54 +0000676 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
677 (ToType->isComplexType() && FromType->isArithmeticType())) {
678 // Complex-real conversions (C99 6.3.1.7)
679 SCS.Second = ICK_Complex_Real;
680 FromType = ToType.getUnqualifiedType();
681 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
682 // Floating point conversions (C++ 4.8).
683 SCS.Second = ICK_Floating_Conversion;
684 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000685 } else if ((FromType->isFloatingType() &&
686 ToType->isIntegralType() && (!ToType->isBooleanType() &&
687 !ToType->isEnumeralType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000688 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000689 ToType->isFloatingType())) {
690 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000691 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000692 FromType = ToType.getUnqualifiedType();
Anders Carlsson08972922009-08-28 15:33:32 +0000693 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
694 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000695 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000696 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000697 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregorce940492009-09-25 04:25:58 +0000698 } else if (IsMemberPointerConversion(From, FromType, ToType,
699 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000700 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000701 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000702 } else if (ToType->isBooleanType() &&
703 (FromType->isArithmeticType() ||
704 FromType->isEnumeralType() ||
Fariborz Jahanian1f7711d2009-12-11 21:23:13 +0000705 FromType->isAnyPointerType() ||
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000706 FromType->isBlockPointerType() ||
707 FromType->isMemberPointerType() ||
708 FromType->isNullPtrType())) {
709 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000710 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000711 FromType = Context.BoolTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000712 } else if (!getLangOptions().CPlusPlus &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000713 Context.typesAreCompatible(ToType, FromType)) {
714 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000715 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor43c79c22009-12-09 00:47:37 +0000716 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
717 // Treat a conversion that strips "noreturn" as an identity conversion.
718 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000719 } else {
720 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000721 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000722 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000723 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000724
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000725 QualType CanonFrom;
726 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000727 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000728 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000729 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000730 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000731 CanonFrom = Context.getCanonicalType(FromType);
732 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000733 } else {
734 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000735 SCS.Third = ICK_Identity;
736
Mike Stump1eb44332009-09-09 15:08:12 +0000737 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +0000738 // [...] Any difference in top-level cv-qualification is
739 // subsumed by the initialization itself and does not constitute
740 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000741 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000742 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +0000743 if (CanonFrom.getLocalUnqualifiedType()
744 == CanonTo.getLocalUnqualifiedType() &&
745 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000746 FromType = ToType;
747 CanonFrom = CanonTo;
748 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000749 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000750 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000751
752 // If we have not converted the argument type to the parameter type,
753 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000754 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000755 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000756
Douglas Gregor60d62c22008-10-31 16:23:19 +0000757 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000758}
759
760/// IsIntegralPromotion - Determines whether the conversion from the
761/// expression From (whose potentially-adjusted type is FromType) to
762/// ToType is an integral promotion (C++ 4.5). If so, returns true and
763/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000764bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000765 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000766 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000767 if (!To) {
768 return false;
769 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000770
771 // An rvalue of type char, signed char, unsigned char, short int, or
772 // unsigned short int can be converted to an rvalue of type int if
773 // int can represent all the values of the source type; otherwise,
774 // the source rvalue can be converted to an rvalue of type unsigned
775 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +0000776 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
777 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000778 if (// We can promote any signed, promotable integer type to an int
779 (FromType->isSignedIntegerType() ||
780 // We can promote any unsigned integer type whose size is
781 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +0000782 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000783 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000784 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000785 }
786
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000787 return To->getKind() == BuiltinType::UInt;
788 }
789
790 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
791 // can be converted to an rvalue of the first of the following types
792 // that can represent all the values of its underlying type: int,
793 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall842aef82009-12-09 09:09:27 +0000794
795 // We pre-calculate the promotion type for enum types.
796 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
797 if (ToType->isIntegerType())
798 return Context.hasSameUnqualifiedType(ToType,
799 FromEnumType->getDecl()->getPromotionType());
800
801 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000802 // Determine whether the type we're converting from is signed or
803 // unsigned.
804 bool FromIsSigned;
805 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +0000806
807 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
808 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000809
810 // The types we'll try to promote to, in the appropriate
811 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +0000812 QualType PromoteTypes[6] = {
813 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000814 Context.LongTy, Context.UnsignedLongTy ,
815 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000816 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000817 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000818 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
819 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +0000820 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000821 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
822 // We found the type that we can promote to. If this is the
823 // type we wanted, we have a promotion. Otherwise, no
824 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000825 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000826 }
827 }
828 }
829
830 // An rvalue for an integral bit-field (9.6) can be converted to an
831 // rvalue of type int if int can represent all the values of the
832 // bit-field; otherwise, it can be converted to unsigned int if
833 // unsigned int can represent all the values of the bit-field. If
834 // the bit-field is larger yet, no integral promotion applies to
835 // it. If the bit-field has an enumerated type, it is treated as any
836 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +0000837 // FIXME: We should delay checking of bit-fields until we actually perform the
838 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000839 using llvm::APSInt;
840 if (From)
841 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +0000842 APSInt BitWidth;
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000843 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
844 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
845 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
846 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Douglas Gregor86f19402008-12-20 23:49:58 +0000848 // Are we promoting to an int from a bitfield that fits in an int?
849 if (BitWidth < ToSize ||
850 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
851 return To->getKind() == BuiltinType::Int;
852 }
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Douglas Gregor86f19402008-12-20 23:49:58 +0000854 // Are we promoting to an unsigned int from an unsigned bitfield
855 // that fits into an unsigned int?
856 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
857 return To->getKind() == BuiltinType::UInt;
858 }
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Douglas Gregor86f19402008-12-20 23:49:58 +0000860 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000861 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000862 }
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000864 // An rvalue of type bool can be converted to an rvalue of type int,
865 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000866 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000867 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000868 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000869
870 return false;
871}
872
873/// IsFloatingPointPromotion - Determines whether the conversion from
874/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
875/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000876bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000877 /// An rvalue of type float can be converted to an rvalue of type
878 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +0000879 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
880 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000881 if (FromBuiltin->getKind() == BuiltinType::Float &&
882 ToBuiltin->getKind() == BuiltinType::Double)
883 return true;
884
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000885 // C99 6.3.1.5p1:
886 // When a float is promoted to double or long double, or a
887 // double is promoted to long double [...].
888 if (!getLangOptions().CPlusPlus &&
889 (FromBuiltin->getKind() == BuiltinType::Float ||
890 FromBuiltin->getKind() == BuiltinType::Double) &&
891 (ToBuiltin->getKind() == BuiltinType::LongDouble))
892 return true;
893 }
894
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000895 return false;
896}
897
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000898/// \brief Determine if a conversion is a complex promotion.
899///
900/// A complex promotion is defined as a complex -> complex conversion
901/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000902/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000903bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000904 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000905 if (!FromComplex)
906 return false;
907
John McCall183700f2009-09-21 23:43:11 +0000908 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000909 if (!ToComplex)
910 return false;
911
912 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000913 ToComplex->getElementType()) ||
914 IsIntegralPromotion(0, FromComplex->getElementType(),
915 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000916}
917
Douglas Gregorcb7de522008-11-26 23:31:11 +0000918/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
919/// the pointer type FromPtr to a pointer to type ToPointee, with the
920/// same type qualifiers as FromPtr has on its pointee type. ToType,
921/// if non-empty, will be a pointer to ToType that may or may not have
922/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +0000923static QualType
924BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000925 QualType ToPointee, QualType ToType,
926 ASTContext &Context) {
927 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
928 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +0000929 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +0000930
931 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000932 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +0000933 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +0000934 if (!ToType.isNull())
Douglas Gregorcb7de522008-11-26 23:31:11 +0000935 return ToType;
936
937 // Build a pointer to ToPointee. It has the right qualifiers
938 // already.
939 return Context.getPointerType(ToPointee);
940 }
941
942 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +0000943 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +0000944 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
945 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +0000946}
947
Fariborz Jahanianadcfab12009-12-16 23:13:33 +0000948/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
949/// the FromType, which is an objective-c pointer, to ToType, which may or may
950/// not have the right set of qualifiers.
951static QualType
952BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
953 QualType ToType,
954 ASTContext &Context) {
955 QualType CanonFromType = Context.getCanonicalType(FromType);
956 QualType CanonToType = Context.getCanonicalType(ToType);
957 Qualifiers Quals = CanonFromType.getQualifiers();
958
959 // Exact qualifier match -> return the pointer type we're converting to.
960 if (CanonToType.getLocalQualifiers() == Quals)
961 return ToType;
962
963 // Just build a canonical type that has the right qualifiers.
964 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
965}
966
Mike Stump1eb44332009-09-09 15:08:12 +0000967static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000968 bool InOverloadResolution,
969 ASTContext &Context) {
970 // Handle value-dependent integral null pointer constants correctly.
971 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
972 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
973 Expr->getType()->isIntegralType())
974 return !InOverloadResolution;
975
Douglas Gregorce940492009-09-25 04:25:58 +0000976 return Expr->isNullPointerConstant(Context,
977 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
978 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000979}
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000981/// IsPointerConversion - Determines whether the conversion of the
982/// expression From, which has the (possibly adjusted) type FromType,
983/// can be converted to the type ToType via a pointer conversion (C++
984/// 4.10). If so, returns true and places the converted type (that
985/// might differ from ToType in its cv-qualifiers at some level) into
986/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000987///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000988/// This routine also supports conversions to and from block pointers
989/// and conversions with Objective-C's 'id', 'id<protocols...>', and
990/// pointers to interfaces. FIXME: Once we've determined the
991/// appropriate overloading rules for Objective-C, we may want to
992/// split the Objective-C checks into a different routine; however,
993/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000994/// conversions, so for now they live here. IncompatibleObjC will be
995/// set if the conversion is an allowed Objective-C conversion that
996/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000997bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000998 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +0000999 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001000 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001001 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +00001002 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1003 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001004
Mike Stump1eb44332009-09-09 15:08:12 +00001005 // Conversion from a null pointer constant to any Objective-C pointer type.
1006 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001007 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001008 ConvertedType = ToType;
1009 return true;
1010 }
1011
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001012 // Blocks: Block pointers can be converted to void*.
1013 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001014 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001015 ConvertedType = ToType;
1016 return true;
1017 }
1018 // Blocks: A null pointer constant can be converted to a block
1019 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001020 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001021 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001022 ConvertedType = ToType;
1023 return true;
1024 }
1025
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001026 // If the left-hand-side is nullptr_t, the right side can be a null
1027 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001028 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001029 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001030 ConvertedType = ToType;
1031 return true;
1032 }
1033
Ted Kremenek6217b802009-07-29 21:53:49 +00001034 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001035 if (!ToTypePtr)
1036 return false;
1037
1038 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001039 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001040 ConvertedType = ToType;
1041 return true;
1042 }
Sebastian Redl07779722008-10-31 14:43:28 +00001043
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001044 // Beyond this point, both types need to be pointers
1045 // , including objective-c pointers.
1046 QualType ToPointeeType = ToTypePtr->getPointeeType();
1047 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1048 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1049 ToType, Context);
1050 return true;
1051
1052 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001053 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001054 if (!FromTypePtr)
1055 return false;
1056
1057 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001058
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001059 // An rvalue of type "pointer to cv T," where T is an object type,
1060 // can be converted to an rvalue of type "pointer to cv void" (C++
1061 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +00001062 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001063 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001064 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001065 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001066 return true;
1067 }
1068
Douglas Gregorf9201e02009-02-11 23:02:49 +00001069 // When we're overloading in C, we allow a special kind of pointer
1070 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001071 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001072 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001073 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001074 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001075 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001076 return true;
1077 }
1078
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001079 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001080 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001081 // An rvalue of type "pointer to cv D," where D is a class type,
1082 // can be converted to an rvalue of type "pointer to cv B," where
1083 // B is a base class (clause 10) of D. If B is an inaccessible
1084 // (clause 11) or ambiguous (10.2) base class of D, a program that
1085 // necessitates this conversion is ill-formed. The result of the
1086 // conversion is a pointer to the base class sub-object of the
1087 // derived class object. The null pointer value is converted to
1088 // the null pointer value of the destination type.
1089 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001090 // Note that we do not check for ambiguity or inaccessibility
1091 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001092 if (getLangOptions().CPlusPlus &&
1093 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001094 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001095 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001096 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001097 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001098 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001099 ToType, Context);
1100 return true;
1101 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001102
Douglas Gregorc7887512008-12-19 19:13:09 +00001103 return false;
1104}
1105
1106/// isObjCPointerConversion - Determines whether this is an
1107/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1108/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001109bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001110 QualType& ConvertedType,
1111 bool &IncompatibleObjC) {
1112 if (!getLangOptions().ObjC1)
1113 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001114
Steve Naroff14108da2009-07-10 23:34:53 +00001115 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001116 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001117 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001118 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001119
Steve Naroff14108da2009-07-10 23:34:53 +00001120 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001121 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001122 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001123 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001124 ConvertedType = ToType;
1125 return true;
1126 }
1127 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001128 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001129 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001130 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001131 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001132 ConvertedType = ToType;
1133 return true;
1134 }
1135 // Objective C++: We're able to convert from a pointer to an
1136 // interface to a pointer to a different interface.
1137 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001138 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1139 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1140 if (getLangOptions().CPlusPlus && LHS && RHS &&
1141 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1142 FromObjCPtr->getPointeeType()))
1143 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00001144 ConvertedType = ToType;
1145 return true;
1146 }
1147
1148 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1149 // Okay: this is some kind of implicit downcast of Objective-C
1150 // interfaces, which is permitted. However, we're going to
1151 // complain about it.
1152 IncompatibleObjC = true;
1153 ConvertedType = FromType;
1154 return true;
1155 }
Mike Stump1eb44332009-09-09 15:08:12 +00001156 }
Steve Naroff14108da2009-07-10 23:34:53 +00001157 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001158 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001159 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001160 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001161 else if (const BlockPointerType *ToBlockPtr =
1162 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001163 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001164 // to a block pointer type.
1165 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1166 ConvertedType = ToType;
1167 return true;
1168 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001169 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001170 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001171 else if (FromType->getAs<BlockPointerType>() &&
1172 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1173 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001174 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001175 ConvertedType = ToType;
1176 return true;
1177 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001178 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001179 return false;
1180
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001181 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001182 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001183 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001184 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001185 FromPointeeType = FromBlockPtr->getPointeeType();
1186 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001187 return false;
1188
Douglas Gregorc7887512008-12-19 19:13:09 +00001189 // If we have pointers to pointers, recursively check whether this
1190 // is an Objective-C conversion.
1191 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1192 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1193 IncompatibleObjC)) {
1194 // We always complain about this conversion.
1195 IncompatibleObjC = true;
1196 ConvertedType = ToType;
1197 return true;
1198 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001199 // Allow conversion of pointee being objective-c pointer to another one;
1200 // as in I* to id.
1201 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1202 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1203 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1204 IncompatibleObjC)) {
1205 ConvertedType = ToType;
1206 return true;
1207 }
1208
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001209 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001210 // differences in the argument and result types are in Objective-C
1211 // pointer conversions. If so, we permit the conversion (but
1212 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001213 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001214 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001215 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001216 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001217 if (FromFunctionType && ToFunctionType) {
1218 // If the function types are exactly the same, this isn't an
1219 // Objective-C pointer conversion.
1220 if (Context.getCanonicalType(FromPointeeType)
1221 == Context.getCanonicalType(ToPointeeType))
1222 return false;
1223
1224 // Perform the quick checks that will tell us whether these
1225 // function types are obviously different.
1226 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1227 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1228 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1229 return false;
1230
1231 bool HasObjCConversion = false;
1232 if (Context.getCanonicalType(FromFunctionType->getResultType())
1233 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1234 // Okay, the types match exactly. Nothing to do.
1235 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1236 ToFunctionType->getResultType(),
1237 ConvertedType, IncompatibleObjC)) {
1238 // Okay, we have an Objective-C pointer conversion.
1239 HasObjCConversion = true;
1240 } else {
1241 // Function types are too different. Abort.
1242 return false;
1243 }
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Douglas Gregorc7887512008-12-19 19:13:09 +00001245 // Check argument types.
1246 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1247 ArgIdx != NumArgs; ++ArgIdx) {
1248 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1249 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1250 if (Context.getCanonicalType(FromArgType)
1251 == Context.getCanonicalType(ToArgType)) {
1252 // Okay, the types match exactly. Nothing to do.
1253 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1254 ConvertedType, IncompatibleObjC)) {
1255 // Okay, we have an Objective-C pointer conversion.
1256 HasObjCConversion = true;
1257 } else {
1258 // Argument types are too different. Abort.
1259 return false;
1260 }
1261 }
1262
1263 if (HasObjCConversion) {
1264 // We had an Objective-C conversion. Allow this pointer
1265 // conversion, but complain about it.
1266 ConvertedType = ToType;
1267 IncompatibleObjC = true;
1268 return true;
1269 }
1270 }
1271
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001272 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001273}
1274
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001275/// CheckPointerConversion - Check the pointer conversion from the
1276/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001277/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001278/// conversions for which IsPointerConversion has already returned
1279/// true. It returns true and produces a diagnostic if there was an
1280/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001281bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001282 CastExpr::CastKind &Kind,
1283 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001284 QualType FromType = From->getType();
1285
Ted Kremenek6217b802009-07-29 21:53:49 +00001286 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1287 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001288 QualType FromPointeeType = FromPtrType->getPointeeType(),
1289 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001290
Douglas Gregor5fccd362010-03-03 23:55:11 +00001291 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1292 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001293 // We must have a derived-to-base conversion. Check an
1294 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001295 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1296 From->getExprLoc(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001297 From->getSourceRange(),
1298 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001299 return true;
1300
1301 // The conversion was successful.
1302 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001303 }
1304 }
Mike Stump1eb44332009-09-09 15:08:12 +00001305 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001306 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001307 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001308 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001309 // Objective-C++ conversions are always okay.
1310 // FIXME: We should have a different class of conversions for the
1311 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001312 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001313 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001314
Steve Naroff14108da2009-07-10 23:34:53 +00001315 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001316 return false;
1317}
1318
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001319/// IsMemberPointerConversion - Determines whether the conversion of the
1320/// expression From, which has the (possibly adjusted) type FromType, can be
1321/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1322/// If so, returns true and places the converted type (that might differ from
1323/// ToType in its cv-qualifiers at some level) into ConvertedType.
1324bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001325 QualType ToType,
1326 bool InOverloadResolution,
1327 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001328 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001329 if (!ToTypePtr)
1330 return false;
1331
1332 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001333 if (From->isNullPointerConstant(Context,
1334 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1335 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001336 ConvertedType = ToType;
1337 return true;
1338 }
1339
1340 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001341 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001342 if (!FromTypePtr)
1343 return false;
1344
1345 // A pointer to member of B can be converted to a pointer to member of D,
1346 // where D is derived from B (C++ 4.11p2).
1347 QualType FromClass(FromTypePtr->getClass(), 0);
1348 QualType ToClass(ToTypePtr->getClass(), 0);
1349 // FIXME: What happens when these are dependent? Is this function even called?
1350
1351 if (IsDerivedFrom(ToClass, FromClass)) {
1352 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1353 ToClass.getTypePtr());
1354 return true;
1355 }
1356
1357 return false;
1358}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001359
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001360/// CheckMemberPointerConversion - Check the member pointer conversion from the
1361/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00001362/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001363/// for which IsMemberPointerConversion has already returned true. It returns
1364/// true and produces a diagnostic if there was an error, or returns false
1365/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001366bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001367 CastExpr::CastKind &Kind,
1368 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001369 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001370 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001371 if (!FromPtrType) {
1372 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001373 assert(From->isNullPointerConstant(Context,
1374 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001375 "Expr must be null pointer constant!");
1376 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001377 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001378 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001379
Ted Kremenek6217b802009-07-29 21:53:49 +00001380 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001381 assert(ToPtrType && "No member pointer cast has a target type "
1382 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001383
Sebastian Redl21593ac2009-01-28 18:33:18 +00001384 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1385 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001386
Sebastian Redl21593ac2009-01-28 18:33:18 +00001387 // FIXME: What about dependent types?
1388 assert(FromClass->isRecordType() && "Pointer into non-class.");
1389 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001390
John McCall6b2accb2010-02-10 09:31:12 +00001391 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/ true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001392 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001393 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1394 assert(DerivationOkay &&
1395 "Should not have been called if derivation isn't OK.");
1396 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001397
Sebastian Redl21593ac2009-01-28 18:33:18 +00001398 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1399 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001400 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1401 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1402 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1403 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001404 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001405
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001406 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001407 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1408 << FromClass << ToClass << QualType(VBase, 0)
1409 << From->getSourceRange();
1410 return true;
1411 }
1412
John McCall6b2accb2010-02-10 09:31:12 +00001413 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00001414 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1415 Paths.front(),
1416 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00001417
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001418 // Must be a base to derived member conversion.
1419 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001420 return false;
1421}
1422
Douglas Gregor98cd5992008-10-21 23:43:52 +00001423/// IsQualificationConversion - Determines whether the conversion from
1424/// an rvalue of type FromType to ToType is a qualification conversion
1425/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001426bool
1427Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001428 FromType = Context.getCanonicalType(FromType);
1429 ToType = Context.getCanonicalType(ToType);
1430
1431 // If FromType and ToType are the same type, this is not a
1432 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00001433 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00001434 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001435
Douglas Gregor98cd5992008-10-21 23:43:52 +00001436 // (C++ 4.4p4):
1437 // A conversion can add cv-qualifiers at levels other than the first
1438 // in multi-level pointers, subject to the following rules: [...]
1439 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001440 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001441 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001442 // Within each iteration of the loop, we check the qualifiers to
1443 // determine if this still looks like a qualification
1444 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001445 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001446 // until there are no more pointers or pointers-to-members left to
1447 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001448 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001449
1450 // -- for every j > 0, if const is in cv 1,j then const is in cv
1451 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001452 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001453 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001454
Douglas Gregor98cd5992008-10-21 23:43:52 +00001455 // -- if the cv 1,j and cv 2,j are different, then const is in
1456 // every cv for 0 < k < j.
1457 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001458 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001459 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001460
Douglas Gregor98cd5992008-10-21 23:43:52 +00001461 // Keep track of whether all prior cv-qualifiers in the "to" type
1462 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001463 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001464 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001465 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001466
1467 // We are left with FromType and ToType being the pointee types
1468 // after unwrapping the original FromType and ToType the same number
1469 // of types. If we unwrapped any pointers, and if FromType and
1470 // ToType have the same unqualified type (since we checked
1471 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001472 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001473}
1474
Douglas Gregor734d9862009-01-30 23:27:23 +00001475/// Determines whether there is a user-defined conversion sequence
1476/// (C++ [over.ics.user]) that converts expression From to the type
1477/// ToType. If such a conversion exists, User will contain the
1478/// user-defined conversion sequence that performs such a conversion
1479/// and this routine will return true. Otherwise, this routine returns
1480/// false and User is unspecified.
1481///
1482/// \param AllowConversionFunctions true if the conversion should
1483/// consider conversion functions at all. If false, only constructors
1484/// will be considered.
1485///
1486/// \param AllowExplicit true if the conversion should consider C++0x
1487/// "explicit" conversion functions as well as non-explicit conversion
1488/// functions (C++0x [class.conv.fct]p2).
Sebastian Redle2b68332009-04-12 17:16:29 +00001489///
1490/// \param ForceRValue true if the expression should be treated as an rvalue
1491/// for overload resolution.
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001492/// \param UserCast true if looking for user defined conversion for a static
1493/// cast.
Douglas Gregor20093b42009-12-09 23:02:17 +00001494OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1495 UserDefinedConversionSequence& User,
1496 OverloadCandidateSet& CandidateSet,
1497 bool AllowConversionFunctions,
1498 bool AllowExplicit,
1499 bool ForceRValue,
1500 bool UserCast) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001501 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00001502 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1503 // We're not going to find any constructors.
1504 } else if (CXXRecordDecl *ToRecordDecl
1505 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001506 // C++ [over.match.ctor]p1:
1507 // When objects of class type are direct-initialized (8.5), or
1508 // copy-initialized from an expression of the same or a
1509 // derived class type (8.5), overload resolution selects the
1510 // constructor. [...] For copy-initialization, the candidate
1511 // functions are all the converting constructors (12.3.1) of
1512 // that class. The argument list is the expression-list within
1513 // the parentheses of the initializer.
Douglas Gregor79b680e2009-11-13 18:44:21 +00001514 bool SuppressUserConversions = !UserCast;
1515 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1516 IsDerivedFrom(From->getType(), ToType)) {
1517 SuppressUserConversions = false;
1518 AllowConversionFunctions = false;
1519 }
1520
Mike Stump1eb44332009-09-09 15:08:12 +00001521 DeclarationName ConstructorName
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001522 = Context.DeclarationNames.getCXXConstructorName(
1523 Context.getCanonicalType(ToType).getUnqualifiedType());
1524 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump1eb44332009-09-09 15:08:12 +00001525 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001526 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001527 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00001528 NamedDecl *D = *Con;
1529 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1530
Douglas Gregordec06662009-08-21 18:42:58 +00001531 // Find the constructor (which may be a template).
1532 CXXConstructorDecl *Constructor = 0;
1533 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00001534 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00001535 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001536 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001537 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1538 else
John McCall9aa472c2010-03-19 07:35:19 +00001539 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001540
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001541 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001542 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001543 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00001544 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001545 /*ExplicitArgs*/ 0,
John McCalld5532b62009-11-23 01:53:49 +00001546 &From, 1, CandidateSet,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001547 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001548 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001549 // Allow one user-defined conversion when user specifies a
1550 // From->ToType conversion via an static cast (c-style, etc).
John McCall9aa472c2010-03-19 07:35:19 +00001551 AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001552 &From, 1, CandidateSet,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001553 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001554 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001555 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001556 }
1557 }
1558
Douglas Gregor734d9862009-01-30 23:27:23 +00001559 if (!AllowConversionFunctions) {
1560 // Don't allow any conversion functions to enter the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00001561 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1562 PDiag(0)
Anders Carlssonb7906612009-08-26 23:45:07 +00001563 << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001564 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001565 } else if (const RecordType *FromRecordType
Ted Kremenek6217b802009-07-29 21:53:49 +00001566 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001567 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001568 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1569 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00001570 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001571 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001572 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001573 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00001574 DeclAccessPair FoundDecl = I.getPair();
1575 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00001576 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1577 if (isa<UsingShadowDecl>(D))
1578 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1579
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001580 CXXConversionDecl *Conv;
1581 FunctionTemplateDecl *ConvTemplate;
John McCallba135432009-11-21 08:51:07 +00001582 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001583 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1584 else
John McCallba135432009-11-21 08:51:07 +00001585 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001586
1587 if (AllowExplicit || !Conv->isExplicit()) {
1588 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00001589 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001590 ActingContext, From, ToType,
1591 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001592 else
John McCall9aa472c2010-03-19 07:35:19 +00001593 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCall86820f52010-01-26 01:37:31 +00001594 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001595 }
1596 }
1597 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001598 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001599
1600 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001601 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001602 case OR_Success:
1603 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001604 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001605 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1606 // C++ [over.ics.user]p1:
1607 // If the user-defined conversion is specified by a
1608 // constructor (12.3.1), the initial standard conversion
1609 // sequence converts the source type to the type required by
1610 // the argument of the constructor.
1611 //
Douglas Gregor60d62c22008-10-31 16:23:19 +00001612 QualType ThisType = Constructor->getThisType(Context);
John McCall1d318332010-01-12 00:44:57 +00001613 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001614 User.EllipsisConversion = true;
1615 else {
1616 User.Before = Best->Conversions[0].Standard;
1617 User.EllipsisConversion = false;
1618 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001619 User.ConversionFunction = Constructor;
1620 User.After.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00001621 User.After.setFromType(
1622 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregorad323a82010-01-27 03:51:04 +00001623 User.After.setAllToTypes(ToType);
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001624 return OR_Success;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001625 } else if (CXXConversionDecl *Conversion
1626 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1627 // C++ [over.ics.user]p1:
1628 //
1629 // [...] If the user-defined conversion is specified by a
1630 // conversion function (12.3.2), the initial standard
1631 // conversion sequence converts the source type to the
1632 // implicit object parameter of the conversion function.
1633 User.Before = Best->Conversions[0].Standard;
1634 User.ConversionFunction = Conversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001635 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001636
1637 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001638 // The second standard conversion sequence converts the
1639 // result of the user-defined conversion to the target type
1640 // for the sequence. Since an implicit conversion sequence
1641 // is an initialization, the special rules for
1642 // initialization by user-defined conversion apply when
1643 // selecting the best user-defined conversion for a
1644 // user-defined conversion sequence (see 13.3.3 and
1645 // 13.3.3.1).
1646 User.After = Best->FinalConversion;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001647 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001648 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001649 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001650 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001651 }
Mike Stump1eb44332009-09-09 15:08:12 +00001652
Douglas Gregor60d62c22008-10-31 16:23:19 +00001653 case OR_No_Viable_Function:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001654 return OR_No_Viable_Function;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001655 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001656 // No conversion here! We're done.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001657 return OR_Deleted;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001658
1659 case OR_Ambiguous:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001660 return OR_Ambiguous;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001661 }
1662
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001663 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001664}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001665
1666bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001667Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001668 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00001669 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001670 OverloadingResult OvResult =
1671 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1672 CandidateSet, true, false, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001673 if (OvResult == OR_Ambiguous)
1674 Diag(From->getSourceRange().getBegin(),
1675 diag::err_typecheck_ambiguous_condition)
1676 << From->getType() << ToType << From->getSourceRange();
1677 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1678 Diag(From->getSourceRange().getBegin(),
1679 diag::err_typecheck_nonviable_condition)
1680 << From->getType() << ToType << From->getSourceRange();
1681 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001682 return false;
John McCallcbce6062010-01-12 07:18:19 +00001683 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001684 return true;
1685}
Douglas Gregor60d62c22008-10-31 16:23:19 +00001686
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001687/// CompareImplicitConversionSequences - Compare two implicit
1688/// conversion sequences to determine whether one is better than the
1689/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00001690ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001691Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1692 const ImplicitConversionSequence& ICS2)
1693{
1694 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1695 // conversion sequences (as defined in 13.3.3.1)
1696 // -- a standard conversion sequence (13.3.3.1.1) is a better
1697 // conversion sequence than a user-defined conversion sequence or
1698 // an ellipsis conversion sequence, and
1699 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1700 // conversion sequence than an ellipsis conversion sequence
1701 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00001702 //
John McCall1d318332010-01-12 00:44:57 +00001703 // C++0x [over.best.ics]p10:
1704 // For the purpose of ranking implicit conversion sequences as
1705 // described in 13.3.3.2, the ambiguous conversion sequence is
1706 // treated as a user-defined sequence that is indistinguishable
1707 // from any other user-defined conversion sequence.
1708 if (ICS1.getKind() < ICS2.getKind()) {
1709 if (!(ICS1.isUserDefined() && ICS2.isAmbiguous()))
1710 return ImplicitConversionSequence::Better;
1711 } else if (ICS2.getKind() < ICS1.getKind()) {
1712 if (!(ICS2.isUserDefined() && ICS1.isAmbiguous()))
1713 return ImplicitConversionSequence::Worse;
1714 }
1715
1716 if (ICS1.isAmbiguous() || ICS2.isAmbiguous())
1717 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001718
1719 // Two implicit conversion sequences of the same form are
1720 // indistinguishable conversion sequences unless one of the
1721 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00001722 if (ICS1.isStandard())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001723 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00001724 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001725 // User-defined conversion sequence U1 is a better conversion
1726 // sequence than another user-defined conversion sequence U2 if
1727 // they contain the same user-defined conversion function or
1728 // constructor and if the second standard conversion sequence of
1729 // U1 is better than the second standard conversion sequence of
1730 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001731 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001732 ICS2.UserDefined.ConversionFunction)
1733 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1734 ICS2.UserDefined.After);
1735 }
1736
1737 return ImplicitConversionSequence::Indistinguishable;
1738}
1739
Douglas Gregorad323a82010-01-27 03:51:04 +00001740// Per 13.3.3.2p3, compare the given standard conversion sequences to
1741// determine if one is a proper subset of the other.
1742static ImplicitConversionSequence::CompareKind
1743compareStandardConversionSubsets(ASTContext &Context,
1744 const StandardConversionSequence& SCS1,
1745 const StandardConversionSequence& SCS2) {
1746 ImplicitConversionSequence::CompareKind Result
1747 = ImplicitConversionSequence::Indistinguishable;
1748
1749 if (SCS1.Second != SCS2.Second) {
1750 if (SCS1.Second == ICK_Identity)
1751 Result = ImplicitConversionSequence::Better;
1752 else if (SCS2.Second == ICK_Identity)
1753 Result = ImplicitConversionSequence::Worse;
1754 else
1755 return ImplicitConversionSequence::Indistinguishable;
1756 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
1757 return ImplicitConversionSequence::Indistinguishable;
1758
1759 if (SCS1.Third == SCS2.Third) {
1760 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
1761 : ImplicitConversionSequence::Indistinguishable;
1762 }
1763
1764 if (SCS1.Third == ICK_Identity)
1765 return Result == ImplicitConversionSequence::Worse
1766 ? ImplicitConversionSequence::Indistinguishable
1767 : ImplicitConversionSequence::Better;
1768
1769 if (SCS2.Third == ICK_Identity)
1770 return Result == ImplicitConversionSequence::Better
1771 ? ImplicitConversionSequence::Indistinguishable
1772 : ImplicitConversionSequence::Worse;
1773
1774 return ImplicitConversionSequence::Indistinguishable;
1775}
1776
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001777/// CompareStandardConversionSequences - Compare two standard
1778/// conversion sequences to determine whether one is better than the
1779/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001780ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001781Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1782 const StandardConversionSequence& SCS2)
1783{
1784 // Standard conversion sequence S1 is a better conversion sequence
1785 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1786
1787 // -- S1 is a proper subsequence of S2 (comparing the conversion
1788 // sequences in the canonical form defined by 13.3.3.1.1,
1789 // excluding any Lvalue Transformation; the identity conversion
1790 // sequence is considered to be a subsequence of any
1791 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00001792 if (ImplicitConversionSequence::CompareKind CK
1793 = compareStandardConversionSubsets(Context, SCS1, SCS2))
1794 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001795
1796 // -- the rank of S1 is better than the rank of S2 (by the rules
1797 // defined below), or, if not that,
1798 ImplicitConversionRank Rank1 = SCS1.getRank();
1799 ImplicitConversionRank Rank2 = SCS2.getRank();
1800 if (Rank1 < Rank2)
1801 return ImplicitConversionSequence::Better;
1802 else if (Rank2 < Rank1)
1803 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001804
Douglas Gregor57373262008-10-22 14:17:15 +00001805 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1806 // are indistinguishable unless one of the following rules
1807 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00001808
Douglas Gregor57373262008-10-22 14:17:15 +00001809 // A conversion that is not a conversion of a pointer, or
1810 // pointer to member, to bool is better than another conversion
1811 // that is such a conversion.
1812 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1813 return SCS2.isPointerConversionToBool()
1814 ? ImplicitConversionSequence::Better
1815 : ImplicitConversionSequence::Worse;
1816
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001817 // C++ [over.ics.rank]p4b2:
1818 //
1819 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001820 // conversion of B* to A* is better than conversion of B* to
1821 // void*, and conversion of A* to void* is better than conversion
1822 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00001823 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001824 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001825 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001826 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001827 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1828 // Exactly one of the conversion sequences is a conversion to
1829 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001830 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1831 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001832 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1833 // Neither conversion sequence converts to a void pointer; compare
1834 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001835 if (ImplicitConversionSequence::CompareKind DerivedCK
1836 = CompareDerivedToBaseConversions(SCS1, SCS2))
1837 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001838 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1839 // Both conversion sequences are conversions to void
1840 // pointers. Compare the source types to determine if there's an
1841 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00001842 QualType FromType1 = SCS1.getFromType();
1843 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001844
1845 // Adjust the types we're converting from via the array-to-pointer
1846 // conversion, if we need to.
1847 if (SCS1.First == ICK_Array_To_Pointer)
1848 FromType1 = Context.getArrayDecayedType(FromType1);
1849 if (SCS2.First == ICK_Array_To_Pointer)
1850 FromType2 = Context.getArrayDecayedType(FromType2);
1851
Douglas Gregor01919692009-12-13 21:37:05 +00001852 QualType FromPointee1
1853 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1854 QualType FromPointee2
1855 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001856
Douglas Gregor01919692009-12-13 21:37:05 +00001857 if (IsDerivedFrom(FromPointee2, FromPointee1))
1858 return ImplicitConversionSequence::Better;
1859 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1860 return ImplicitConversionSequence::Worse;
1861
1862 // Objective-C++: If one interface is more specific than the
1863 // other, it is the better one.
1864 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1865 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1866 if (FromIface1 && FromIface1) {
1867 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1868 return ImplicitConversionSequence::Better;
1869 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1870 return ImplicitConversionSequence::Worse;
1871 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001872 }
Douglas Gregor57373262008-10-22 14:17:15 +00001873
1874 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1875 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00001876 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001877 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001878 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001879
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001880 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001881 // C++0x [over.ics.rank]p3b4:
1882 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1883 // implicit object parameter of a non-static member function declared
1884 // without a ref-qualifier, and S1 binds an rvalue reference to an
1885 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00001886 // FIXME: We don't know if we're dealing with the implicit object parameter,
1887 // or if the member function in this case has a ref qualifier.
1888 // (Of course, we don't have ref qualifiers yet.)
1889 if (SCS1.RRefBinding != SCS2.RRefBinding)
1890 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1891 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001892
1893 // C++ [over.ics.rank]p3b4:
1894 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1895 // which the references refer are the same type except for
1896 // top-level cv-qualifiers, and the type to which the reference
1897 // initialized by S2 refers is more cv-qualified than the type
1898 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00001899 QualType T1 = SCS1.getToType(2);
1900 QualType T2 = SCS2.getToType(2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001901 T1 = Context.getCanonicalType(T1);
1902 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00001903 Qualifiers T1Quals, T2Quals;
1904 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1905 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1906 if (UnqualT1 == UnqualT2) {
1907 // If the type is an array type, promote the element qualifiers to the type
1908 // for comparison.
1909 if (isa<ArrayType>(T1) && T1Quals)
1910 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1911 if (isa<ArrayType>(T2) && T2Quals)
1912 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001913 if (T2.isMoreQualifiedThan(T1))
1914 return ImplicitConversionSequence::Better;
1915 else if (T1.isMoreQualifiedThan(T2))
1916 return ImplicitConversionSequence::Worse;
1917 }
1918 }
Douglas Gregor57373262008-10-22 14:17:15 +00001919
1920 return ImplicitConversionSequence::Indistinguishable;
1921}
1922
1923/// CompareQualificationConversions - Compares two standard conversion
1924/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00001925/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1926ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00001927Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00001928 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00001929 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001930 // -- S1 and S2 differ only in their qualification conversion and
1931 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1932 // cv-qualification signature of type T1 is a proper subset of
1933 // the cv-qualification signature of type T2, and S1 is not the
1934 // deprecated string literal array-to-pointer conversion (4.2).
1935 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1936 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1937 return ImplicitConversionSequence::Indistinguishable;
1938
1939 // FIXME: the example in the standard doesn't use a qualification
1940 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00001941 QualType T1 = SCS1.getToType(2);
1942 QualType T2 = SCS2.getToType(2);
Douglas Gregor57373262008-10-22 14:17:15 +00001943 T1 = Context.getCanonicalType(T1);
1944 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00001945 Qualifiers T1Quals, T2Quals;
1946 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1947 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00001948
1949 // If the types are the same, we won't learn anything by unwrapped
1950 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00001951 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00001952 return ImplicitConversionSequence::Indistinguishable;
1953
Chandler Carruth28e318c2009-12-29 07:16:59 +00001954 // If the type is an array type, promote the element qualifiers to the type
1955 // for comparison.
1956 if (isa<ArrayType>(T1) && T1Quals)
1957 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1958 if (isa<ArrayType>(T2) && T2Quals)
1959 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1960
Mike Stump1eb44332009-09-09 15:08:12 +00001961 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00001962 = ImplicitConversionSequence::Indistinguishable;
1963 while (UnwrapSimilarPointerTypes(T1, T2)) {
1964 // Within each iteration of the loop, we check the qualifiers to
1965 // determine if this still looks like a qualification
1966 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001967 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001968 // until there are no more pointers or pointers-to-members left
1969 // to unwrap. This essentially mimics what
1970 // IsQualificationConversion does, but here we're checking for a
1971 // strict subset of qualifiers.
1972 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1973 // The qualifiers are the same, so this doesn't tell us anything
1974 // about how the sequences rank.
1975 ;
1976 else if (T2.isMoreQualifiedThan(T1)) {
1977 // T1 has fewer qualifiers, so it could be the better sequence.
1978 if (Result == ImplicitConversionSequence::Worse)
1979 // Neither has qualifiers that are a subset of the other's
1980 // qualifiers.
1981 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Douglas Gregor57373262008-10-22 14:17:15 +00001983 Result = ImplicitConversionSequence::Better;
1984 } else if (T1.isMoreQualifiedThan(T2)) {
1985 // T2 has fewer qualifiers, so it could be the better sequence.
1986 if (Result == ImplicitConversionSequence::Better)
1987 // Neither has qualifiers that are a subset of the other's
1988 // qualifiers.
1989 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001990
Douglas Gregor57373262008-10-22 14:17:15 +00001991 Result = ImplicitConversionSequence::Worse;
1992 } else {
1993 // Qualifiers are disjoint.
1994 return ImplicitConversionSequence::Indistinguishable;
1995 }
1996
1997 // If the types after this point are equivalent, we're done.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001998 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00001999 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002000 }
2001
Douglas Gregor57373262008-10-22 14:17:15 +00002002 // Check that the winning standard conversion sequence isn't using
2003 // the deprecated string literal array to pointer conversion.
2004 switch (Result) {
2005 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002006 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002007 Result = ImplicitConversionSequence::Indistinguishable;
2008 break;
2009
2010 case ImplicitConversionSequence::Indistinguishable:
2011 break;
2012
2013 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002014 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002015 Result = ImplicitConversionSequence::Indistinguishable;
2016 break;
2017 }
2018
2019 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002020}
2021
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002022/// CompareDerivedToBaseConversions - Compares two standard conversion
2023/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002024/// various kinds of derived-to-base conversions (C++
2025/// [over.ics.rank]p4b3). As part of these checks, we also look at
2026/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002027ImplicitConversionSequence::CompareKind
2028Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2029 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002030 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002031 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002032 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002033 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002034
2035 // Adjust the types we're converting from via the array-to-pointer
2036 // conversion, if we need to.
2037 if (SCS1.First == ICK_Array_To_Pointer)
2038 FromType1 = Context.getArrayDecayedType(FromType1);
2039 if (SCS2.First == ICK_Array_To_Pointer)
2040 FromType2 = Context.getArrayDecayedType(FromType2);
2041
2042 // Canonicalize all of the types.
2043 FromType1 = Context.getCanonicalType(FromType1);
2044 ToType1 = Context.getCanonicalType(ToType1);
2045 FromType2 = Context.getCanonicalType(FromType2);
2046 ToType2 = Context.getCanonicalType(ToType2);
2047
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002048 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002049 //
2050 // If class B is derived directly or indirectly from class A and
2051 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002052 //
2053 // For Objective-C, we let A, B, and C also be Objective-C
2054 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002055
2056 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002057 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002058 SCS2.Second == ICK_Pointer_Conversion &&
2059 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2060 FromType1->isPointerType() && FromType2->isPointerType() &&
2061 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002062 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002063 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002064 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002065 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002066 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002067 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002068 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002069 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002070
John McCall183700f2009-09-21 23:43:11 +00002071 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2072 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2073 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2074 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002075
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002076 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002077 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2078 if (IsDerivedFrom(ToPointee1, ToPointee2))
2079 return ImplicitConversionSequence::Better;
2080 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2081 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002082
2083 if (ToIface1 && ToIface2) {
2084 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2085 return ImplicitConversionSequence::Better;
2086 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2087 return ImplicitConversionSequence::Worse;
2088 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002089 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002090
2091 // -- conversion of B* to A* is better than conversion of C* to A*,
2092 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2093 if (IsDerivedFrom(FromPointee2, FromPointee1))
2094 return ImplicitConversionSequence::Better;
2095 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2096 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Douglas Gregorcb7de522008-11-26 23:31:11 +00002098 if (FromIface1 && FromIface2) {
2099 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2100 return ImplicitConversionSequence::Better;
2101 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2102 return ImplicitConversionSequence::Worse;
2103 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002104 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002105 }
2106
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002107 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002108 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2109 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2110 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2111 const MemberPointerType * FromMemPointer1 =
2112 FromType1->getAs<MemberPointerType>();
2113 const MemberPointerType * ToMemPointer1 =
2114 ToType1->getAs<MemberPointerType>();
2115 const MemberPointerType * FromMemPointer2 =
2116 FromType2->getAs<MemberPointerType>();
2117 const MemberPointerType * ToMemPointer2 =
2118 ToType2->getAs<MemberPointerType>();
2119 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2120 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2121 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2122 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2123 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2124 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2125 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2126 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002127 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002128 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2129 if (IsDerivedFrom(ToPointee1, ToPointee2))
2130 return ImplicitConversionSequence::Worse;
2131 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2132 return ImplicitConversionSequence::Better;
2133 }
2134 // conversion of B::* to C::* is better than conversion of A::* to C::*
2135 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2136 if (IsDerivedFrom(FromPointee1, FromPointee2))
2137 return ImplicitConversionSequence::Better;
2138 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2139 return ImplicitConversionSequence::Worse;
2140 }
2141 }
2142
Douglas Gregor9e239322010-02-25 19:01:05 +00002143 if ((SCS1.ReferenceBinding || SCS1.CopyConstructor) &&
2144 (SCS2.ReferenceBinding || SCS2.CopyConstructor) &&
Douglas Gregor225c41e2008-11-03 19:09:14 +00002145 SCS1.Second == ICK_Derived_To_Base) {
2146 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00002147 // -- binding of an expression of type C to a reference of type
2148 // B& is better than binding an expression of type C to a
2149 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002150 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2151 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002152 if (IsDerivedFrom(ToType1, ToType2))
2153 return ImplicitConversionSequence::Better;
2154 else if (IsDerivedFrom(ToType2, ToType1))
2155 return ImplicitConversionSequence::Worse;
2156 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002157
Douglas Gregor225c41e2008-11-03 19:09:14 +00002158 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00002159 // -- binding of an expression of type B to a reference of type
2160 // A& is better than binding an expression of type C to a
2161 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002162 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2163 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002164 if (IsDerivedFrom(FromType2, FromType1))
2165 return ImplicitConversionSequence::Better;
2166 else if (IsDerivedFrom(FromType1, FromType2))
2167 return ImplicitConversionSequence::Worse;
2168 }
2169 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002170
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002171 return ImplicitConversionSequence::Indistinguishable;
2172}
2173
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002174/// TryCopyInitialization - Try to copy-initialize a value of type
2175/// ToType from the expression From. Return the implicit conversion
2176/// sequence required to pass this argument, which may be a bad
2177/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00002178/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redle2b68332009-04-12 17:16:29 +00002179/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2180/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00002181ImplicitConversionSequence
2182Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002183 bool SuppressUserConversions, bool ForceRValue,
2184 bool InOverloadResolution) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00002185 if (ToType->isReferenceType()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002186 ImplicitConversionSequence ICS;
John McCallb1bdc622010-02-25 01:37:24 +00002187 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00002188 CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00002189 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002190 SuppressUserConversions,
2191 /*AllowExplicit=*/false,
2192 ForceRValue,
2193 &ICS);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002194 return ICS;
2195 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002196 return TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002197 SuppressUserConversions,
2198 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002199 ForceRValue,
2200 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002201 }
2202}
2203
Douglas Gregor96176b32008-11-18 23:14:02 +00002204/// TryObjectArgumentInitialization - Try to initialize the object
2205/// parameter of the given member function (@c Method) from the
2206/// expression @p From.
2207ImplicitConversionSequence
John McCall651f3ee2010-01-14 03:28:57 +00002208Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall701c89e2009-12-03 04:06:58 +00002209 CXXMethodDecl *Method,
2210 CXXRecordDecl *ActingContext) {
2211 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002212 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2213 // const volatile object.
2214 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2215 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2216 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00002217
2218 // Set up the conversion sequence as a "bad" conversion, to allow us
2219 // to exit early.
2220 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00002221
2222 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00002223 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002224 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00002225 FromType = PT->getPointeeType();
2226
2227 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002228
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002229 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00002230 // where X is the class of which the function is a member
2231 // (C++ [over.match.funcs]p4). However, when finding an implicit
2232 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00002233 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00002234 // (C++ [over.match.funcs]p5). We perform a simplified version of
2235 // reference binding here, that allows class rvalues to bind to
2236 // non-constant references.
2237
2238 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2239 // with the implicit object parameter (C++ [over.match.funcs]p5).
2240 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002241 if (ImplicitParamType.getCVRQualifiers()
2242 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00002243 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00002244 ICS.setBad(BadConversionSequence::bad_qualifiers,
2245 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002246 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002247 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002248
2249 // Check that we have either the same type or a derived type. It
2250 // affects the conversion rank.
2251 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00002252 ImplicitConversionKind SecondKind;
2253 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2254 SecondKind = ICK_Identity;
2255 } else if (IsDerivedFrom(FromType, ClassType))
2256 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00002257 else {
John McCallb1bdc622010-02-25 01:37:24 +00002258 ICS.setBad(BadConversionSequence::unrelated_class,
2259 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002260 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002261 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002262
2263 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00002264 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00002265 ICS.Standard.setAsIdentityConversion();
2266 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00002267 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00002268 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002269 ICS.Standard.ReferenceBinding = true;
2270 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00002271 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002272 return ICS;
2273}
2274
2275/// PerformObjectArgumentInitialization - Perform initialization of
2276/// the implicit object parameter for the given Method with the given
2277/// expression.
2278bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00002279Sema::PerformObjectArgumentInitialization(Expr *&From,
2280 NestedNameSpecifier *Qualifier,
2281 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002282 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00002283 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00002284 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002285
Ted Kremenek6217b802009-07-29 21:53:49 +00002286 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002287 FromRecordType = PT->getPointeeType();
2288 DestType = Method->getThisType(Context);
2289 } else {
2290 FromRecordType = From->getType();
2291 DestType = ImplicitParamRecordType;
2292 }
2293
John McCall701c89e2009-12-03 04:06:58 +00002294 // Note that we always use the true parent context when performing
2295 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002296 ImplicitConversionSequence ICS
John McCall701c89e2009-12-03 04:06:58 +00002297 = TryObjectArgumentInitialization(From->getType(), Method,
2298 Method->getParent());
John McCall1d318332010-01-12 00:44:57 +00002299 if (ICS.isBad())
Douglas Gregor96176b32008-11-18 23:14:02 +00002300 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002301 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00002302 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002303
Douglas Gregor5fccd362010-03-03 23:55:11 +00002304 if (ICS.Standard.Second == ICK_Derived_To_Base)
2305 return PerformObjectMemberConversion(From, Qualifier, Method);
Douglas Gregor96176b32008-11-18 23:14:02 +00002306
Douglas Gregor5fccd362010-03-03 23:55:11 +00002307 if (!Context.hasSameType(From->getType(), DestType))
2308 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2309 /*isLvalue=*/!From->getType()->getAs<PointerType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00002310 return false;
2311}
2312
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002313/// TryContextuallyConvertToBool - Attempt to contextually convert the
2314/// expression From to bool (C++0x [conv]p3).
2315ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump1eb44332009-09-09 15:08:12 +00002316 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002317 // FIXME: Are these flags correct?
2318 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00002319 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00002320 /*ForceRValue=*/false,
2321 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002322}
2323
2324/// PerformContextuallyConvertToBool - Perform a contextual conversion
2325/// of the expression From to bool (C++0x [conv]p3).
2326bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2327 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall1d318332010-01-12 00:44:57 +00002328 if (!ICS.isBad())
2329 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002330
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002331 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002332 return Diag(From->getSourceRange().getBegin(),
2333 diag::err_typecheck_bool_condition)
2334 << From->getType() << From->getSourceRange();
2335 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002336}
2337
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002338/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00002339/// candidate functions, using the given function call arguments. If
2340/// @p SuppressUserConversions, then don't allow user-defined
2341/// conversions via constructors or conversion operators.
Sebastian Redle2b68332009-04-12 17:16:29 +00002342/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2343/// hacky way to implement the overloading rules for elidable copy
2344/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002345///
2346/// \para PartialOverloading true if we are performing "partial" overloading
2347/// based on an incomplete set of function arguments. This feature is used by
2348/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00002349void
2350Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002351 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002352 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002353 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00002354 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002355 bool ForceRValue,
2356 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00002357 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002358 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002359 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00002360 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00002361 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00002362
Douglas Gregor88a35142008-12-22 05:46:06 +00002363 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002364 if (!isa<CXXConstructorDecl>(Method)) {
2365 // If we get here, it's because we're calling a member function
2366 // that is named without a member access expression (e.g.,
2367 // "this->f") that was either written explicitly or created
2368 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00002369 // function, e.g., X::f(). We use an empty type for the implied
2370 // object argument (C++ [over.call.func]p3), and the acting context
2371 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00002372 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00002373 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002374 SuppressUserConversions, ForceRValue);
2375 return;
2376 }
2377 // We treat a constructor like a non-member function, since its object
2378 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00002379 }
2380
Douglas Gregorfd476482009-11-13 23:59:09 +00002381 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00002382 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00002383
Douglas Gregor7edfb692009-11-23 12:27:39 +00002384 // Overload resolution is always an unevaluated context.
2385 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2386
Douglas Gregor66724ea2009-11-14 01:20:54 +00002387 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2388 // C++ [class.copy]p3:
2389 // A member function template is never instantiated to perform the copy
2390 // of a class object to an object of its class type.
2391 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2392 if (NumArgs == 1 &&
2393 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor12116062010-02-21 18:30:38 +00002394 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
2395 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00002396 return;
2397 }
2398
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002399 // Add this candidate
2400 CandidateSet.push_back(OverloadCandidate());
2401 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00002402 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002403 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00002404 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002405 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002406 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002407
2408 unsigned NumArgsInProto = Proto->getNumArgs();
2409
2410 // (C++ 13.3.2p2): A candidate function having fewer than m
2411 // parameters is viable only if it has an ellipsis in its parameter
2412 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00002413 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2414 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002415 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002416 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002417 return;
2418 }
2419
2420 // (C++ 13.3.2p2): A candidate function having more than m parameters
2421 // is viable only if the (m+1)st parameter has a default argument
2422 // (8.3.6). For the purposes of overload resolution, the
2423 // parameter list is truncated on the right, so that there are
2424 // exactly m parameters.
2425 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002426 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002427 // Not enough arguments.
2428 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002429 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002430 return;
2431 }
2432
2433 // Determine the implicit conversion sequences for each of the
2434 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002435 Candidate.Conversions.resize(NumArgs);
2436 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2437 if (ArgIdx < NumArgsInProto) {
2438 // (C++ 13.3.2p3): for F to be a viable function, there shall
2439 // exist for each argument an implicit conversion sequence
2440 // (13.3.3.1) that converts that argument to the corresponding
2441 // parameter of F.
2442 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002443 Candidate.Conversions[ArgIdx]
2444 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002445 SuppressUserConversions, ForceRValue,
2446 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00002447 if (Candidate.Conversions[ArgIdx].isBad()) {
2448 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002449 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00002450 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00002451 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002452 } else {
2453 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2454 // argument for which there is no corresponding parameter is
2455 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00002456 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002457 }
2458 }
2459}
2460
Douglas Gregor063daf62009-03-13 18:40:31 +00002461/// \brief Add all of the function declarations in the given function set to
2462/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00002463void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00002464 Expr **Args, unsigned NumArgs,
2465 OverloadCandidateSet& CandidateSet,
2466 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00002467 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00002468 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
2469 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002470 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00002471 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00002472 cast<CXXMethodDecl>(FD)->getParent(),
2473 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00002474 CandidateSet, SuppressUserConversions);
2475 else
John McCall9aa472c2010-03-19 07:35:19 +00002476 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00002477 SuppressUserConversions);
2478 } else {
John McCall9aa472c2010-03-19 07:35:19 +00002479 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00002480 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2481 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00002482 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00002483 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00002484 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00002485 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00002486 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00002487 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00002488 else
John McCall9aa472c2010-03-19 07:35:19 +00002489 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00002490 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00002491 Args, NumArgs, CandidateSet,
2492 SuppressUserConversions);
2493 }
Douglas Gregor364e0212009-06-27 21:05:07 +00002494 }
Douglas Gregor063daf62009-03-13 18:40:31 +00002495}
2496
John McCall314be4e2009-11-17 07:50:12 +00002497/// AddMethodCandidate - Adds a named decl (which is some kind of
2498/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00002499void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00002500 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00002501 Expr **Args, unsigned NumArgs,
2502 OverloadCandidateSet& CandidateSet,
2503 bool SuppressUserConversions, bool ForceRValue) {
John McCall9aa472c2010-03-19 07:35:19 +00002504 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00002505 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00002506
2507 if (isa<UsingShadowDecl>(Decl))
2508 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2509
2510 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2511 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2512 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00002513 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
2514 /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00002515 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00002516 CandidateSet,
2517 SuppressUserConversions,
2518 ForceRValue);
2519 } else {
John McCall9aa472c2010-03-19 07:35:19 +00002520 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00002521 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00002522 CandidateSet, SuppressUserConversions, ForceRValue);
2523 }
2524}
2525
Douglas Gregor96176b32008-11-18 23:14:02 +00002526/// AddMethodCandidate - Adds the given C++ member function to the set
2527/// of candidate functions, using the given function call arguments
2528/// and the object argument (@c Object). For example, in a call
2529/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2530/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2531/// allow user-defined conversions via constructors or conversion
Sebastian Redle2b68332009-04-12 17:16:29 +00002532/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2533/// a slightly hacky way to implement the overloading rules for elidable copy
2534/// initialization in C++0x (C++0x 12.8p15).
Mike Stump1eb44332009-09-09 15:08:12 +00002535void
John McCall9aa472c2010-03-19 07:35:19 +00002536Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002537 CXXRecordDecl *ActingContext, QualType ObjectType,
2538 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00002539 OverloadCandidateSet& CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00002540 bool SuppressUserConversions, bool ForceRValue) {
2541 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002542 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00002543 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002544 assert(!isa<CXXConstructorDecl>(Method) &&
2545 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00002546
Douglas Gregor3f396022009-09-28 04:47:19 +00002547 if (!CandidateSet.isNewCandidate(Method))
2548 return;
2549
Douglas Gregor7edfb692009-11-23 12:27:39 +00002550 // Overload resolution is always an unevaluated context.
2551 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2552
Douglas Gregor96176b32008-11-18 23:14:02 +00002553 // Add this candidate
2554 CandidateSet.push_back(OverloadCandidate());
2555 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00002556 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00002557 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002558 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002559 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002560
2561 unsigned NumArgsInProto = Proto->getNumArgs();
2562
2563 // (C++ 13.3.2p2): A candidate function having fewer than m
2564 // parameters is viable only if it has an ellipsis in its parameter
2565 // list (8.3.5).
2566 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2567 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002568 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00002569 return;
2570 }
2571
2572 // (C++ 13.3.2p2): A candidate function having more than m parameters
2573 // is viable only if the (m+1)st parameter has a default argument
2574 // (8.3.6). For the purposes of overload resolution, the
2575 // parameter list is truncated on the right, so that there are
2576 // exactly m parameters.
2577 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2578 if (NumArgs < MinRequiredArgs) {
2579 // Not enough arguments.
2580 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002581 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00002582 return;
2583 }
2584
2585 Candidate.Viable = true;
2586 Candidate.Conversions.resize(NumArgs + 1);
2587
John McCall701c89e2009-12-03 04:06:58 +00002588 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00002589 // The implicit object argument is ignored.
2590 Candidate.IgnoreObjectArgument = true;
2591 else {
2592 // Determine the implicit conversion sequence for the object
2593 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00002594 Candidate.Conversions[0]
2595 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00002596 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002597 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002598 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00002599 return;
2600 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002601 }
2602
2603 // Determine the implicit conversion sequences for each of the
2604 // arguments.
2605 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2606 if (ArgIdx < NumArgsInProto) {
2607 // (C++ 13.3.2p3): for F to be a viable function, there shall
2608 // exist for each argument an implicit conversion sequence
2609 // (13.3.3.1) that converts that argument to the corresponding
2610 // parameter of F.
2611 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002612 Candidate.Conversions[ArgIdx + 1]
2613 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002614 SuppressUserConversions, ForceRValue,
Anders Carlsson08972922009-08-28 15:33:32 +00002615 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00002616 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002617 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002618 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00002619 break;
2620 }
2621 } else {
2622 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2623 // argument for which there is no corresponding parameter is
2624 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00002625 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00002626 }
2627 }
2628}
2629
Douglas Gregor6b906862009-08-21 00:16:32 +00002630/// \brief Add a C++ member function template as a candidate to the candidate
2631/// set, using template argument deduction to produce an appropriate member
2632/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002633void
Douglas Gregor6b906862009-08-21 00:16:32 +00002634Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00002635 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00002636 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00002637 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00002638 QualType ObjectType,
2639 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002640 OverloadCandidateSet& CandidateSet,
2641 bool SuppressUserConversions,
2642 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002643 if (!CandidateSet.isNewCandidate(MethodTmpl))
2644 return;
2645
Douglas Gregor6b906862009-08-21 00:16:32 +00002646 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002647 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00002648 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002649 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00002650 // candidate functions in the usual way.113) A given name can refer to one
2651 // or more function templates and also to a set of overloaded non-template
2652 // functions. In such a case, the candidate functions generated from each
2653 // function template are combined with the set of non-template candidate
2654 // functions.
John McCall5769d612010-02-08 23:07:23 +00002655 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00002656 FunctionDecl *Specialization = 0;
2657 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00002658 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002659 Args, NumArgs, Specialization, Info)) {
2660 // FIXME: Record what happened with template argument deduction, so
2661 // that we can give the user a beautiful diagnostic.
2662 (void)Result;
2663 return;
2664 }
Mike Stump1eb44332009-09-09 15:08:12 +00002665
Douglas Gregor6b906862009-08-21 00:16:32 +00002666 // Add the function template specialization produced by template argument
2667 // deduction as a candidate.
2668 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00002669 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00002670 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00002671 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002672 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002673 CandidateSet, SuppressUserConversions, ForceRValue);
2674}
2675
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002676/// \brief Add a C++ function template specialization as a candidate
2677/// in the candidate set, using template argument deduction to produce
2678/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002679void
Douglas Gregore53060f2009-06-25 22:08:12 +00002680Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00002681 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00002682 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002683 Expr **Args, unsigned NumArgs,
2684 OverloadCandidateSet& CandidateSet,
2685 bool SuppressUserConversions,
2686 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002687 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2688 return;
2689
Douglas Gregore53060f2009-06-25 22:08:12 +00002690 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002691 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00002692 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002693 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00002694 // candidate functions in the usual way.113) A given name can refer to one
2695 // or more function templates and also to a set of overloaded non-template
2696 // functions. In such a case, the candidate functions generated from each
2697 // function template are combined with the set of non-template candidate
2698 // functions.
John McCall5769d612010-02-08 23:07:23 +00002699 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00002700 FunctionDecl *Specialization = 0;
2701 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00002702 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002703 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00002704 CandidateSet.push_back(OverloadCandidate());
2705 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00002706 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00002707 Candidate.Function = FunctionTemplate->getTemplatedDecl();
2708 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002709 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00002710 Candidate.IsSurrogate = false;
2711 Candidate.IgnoreObjectArgument = false;
John McCall342fec42010-02-01 18:53:26 +00002712
2713 // TODO: record more information about failed template arguments
2714 Candidate.DeductionFailure.Result = Result;
2715 Candidate.DeductionFailure.TemplateParameter = Info.Param.getOpaqueValue();
Douglas Gregore53060f2009-06-25 22:08:12 +00002716 return;
2717 }
Mike Stump1eb44332009-09-09 15:08:12 +00002718
Douglas Gregore53060f2009-06-25 22:08:12 +00002719 // Add the function template specialization produced by template argument
2720 // deduction as a candidate.
2721 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00002722 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregore53060f2009-06-25 22:08:12 +00002723 SuppressUserConversions, ForceRValue);
2724}
Mike Stump1eb44332009-09-09 15:08:12 +00002725
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002726/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00002727/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002728/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00002729/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002730/// (which may or may not be the same type as the type that the
2731/// conversion function produces).
2732void
2733Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00002734 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00002735 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002736 Expr *From, QualType ToType,
2737 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002738 assert(!Conversion->getDescribedFunctionTemplate() &&
2739 "Conversion function templates use AddTemplateConversionCandidate");
2740
Douglas Gregor3f396022009-09-28 04:47:19 +00002741 if (!CandidateSet.isNewCandidate(Conversion))
2742 return;
2743
Douglas Gregor7edfb692009-11-23 12:27:39 +00002744 // Overload resolution is always an unevaluated context.
2745 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2746
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002747 // Add this candidate
2748 CandidateSet.push_back(OverloadCandidate());
2749 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00002750 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002751 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002752 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002753 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002754 Candidate.FinalConversion.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00002755 Candidate.FinalConversion.setFromType(Conversion->getConversionType());
Douglas Gregorad323a82010-01-27 03:51:04 +00002756 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002757
Douglas Gregor96176b32008-11-18 23:14:02 +00002758 // Determine the implicit conversion sequence for the implicit
2759 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002760 Candidate.Viable = true;
2761 Candidate.Conversions.resize(1);
John McCall701c89e2009-12-03 04:06:58 +00002762 Candidate.Conversions[0]
2763 = TryObjectArgumentInitialization(From->getType(), Conversion,
2764 ActingContext);
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002765 // Conversion functions to a different type in the base class is visible in
2766 // the derived class. So, a derived to base conversion should not participate
2767 // in overload resolution.
2768 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2769 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall1d318332010-01-12 00:44:57 +00002770 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002771 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002772 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002773 return;
2774 }
Fariborz Jahanian3759a032009-10-19 19:18:20 +00002775
2776 // We won't go through a user-define type conversion function to convert a
2777 // derived to base as such conversions are given Conversion Rank. They only
2778 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2779 QualType FromCanon
2780 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2781 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2782 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2783 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00002784 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00002785 return;
2786 }
2787
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002788
2789 // To determine what the conversion from the result of calling the
2790 // conversion function to the type we're eventually trying to
2791 // convert to (ToType), we need to synthesize a call to the
2792 // conversion function and attempt copy initialization from it. This
2793 // makes sure that we get the right semantics with respect to
2794 // lvalues/rvalues and the type. Fortunately, we can allocate this
2795 // call on the stack and we don't need its arguments to be
2796 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00002797 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002798 From->getLocStart());
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002799 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman73c39ab2009-10-20 08:27:19 +00002800 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002801 &ConversionRef, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002802
2803 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00002804 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2805 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00002806 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002807 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002808 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00002809 ImplicitConversionSequence ICS =
2810 TryCopyInitialization(&Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002811 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002812 /*ForceRValue=*/false,
2813 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002814
John McCall1d318332010-01-12 00:44:57 +00002815 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002816 case ImplicitConversionSequence::StandardConversion:
2817 Candidate.FinalConversion = ICS.Standard;
2818 break;
2819
2820 case ImplicitConversionSequence::BadConversion:
2821 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00002822 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002823 break;
2824
2825 default:
Mike Stump1eb44332009-09-09 15:08:12 +00002826 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002827 "Can only end up with a standard conversion sequence or failure");
2828 }
2829}
2830
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002831/// \brief Adds a conversion function template specialization
2832/// candidate to the overload set, using template argument deduction
2833/// to deduce the template arguments of the conversion function
2834/// template from the type that we are converting to (C++
2835/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00002836void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002837Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00002838 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00002839 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002840 Expr *From, QualType ToType,
2841 OverloadCandidateSet &CandidateSet) {
2842 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2843 "Only conversion function templates permitted here");
2844
Douglas Gregor3f396022009-09-28 04:47:19 +00002845 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2846 return;
2847
John McCall5769d612010-02-08 23:07:23 +00002848 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002849 CXXConversionDecl *Specialization = 0;
2850 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00002851 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002852 Specialization, Info)) {
2853 // FIXME: Record what happened with template argument deduction, so
2854 // that we can give the user a beautiful diagnostic.
2855 (void)Result;
2856 return;
2857 }
Mike Stump1eb44332009-09-09 15:08:12 +00002858
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002859 // Add the conversion function template specialization produced by
2860 // template argument deduction as a candidate.
2861 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00002862 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00002863 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002864}
2865
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002866/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2867/// converts the given @c Object to a function pointer via the
2868/// conversion function @c Conversion, and then attempts to call it
2869/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2870/// the type of function that we'll eventually be calling.
2871void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00002872 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00002873 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00002874 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00002875 QualType ObjectType,
2876 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002877 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002878 if (!CandidateSet.isNewCandidate(Conversion))
2879 return;
2880
Douglas Gregor7edfb692009-11-23 12:27:39 +00002881 // Overload resolution is always an unevaluated context.
2882 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2883
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002884 CandidateSet.push_back(OverloadCandidate());
2885 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00002886 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002887 Candidate.Function = 0;
2888 Candidate.Surrogate = Conversion;
2889 Candidate.Viable = true;
2890 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002891 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002892 Candidate.Conversions.resize(NumArgs + 1);
2893
2894 // Determine the implicit conversion sequence for the implicit
2895 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00002896 ImplicitConversionSequence ObjectInit
John McCall701c89e2009-12-03 04:06:58 +00002897 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00002898 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002899 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002900 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00002901 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002902 return;
2903 }
2904
2905 // The first conversion is actually a user-defined conversion whose
2906 // first conversion is ObjectInit's standard conversion (which is
2907 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00002908 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002909 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002910 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002911 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00002912 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002913 = Candidate.Conversions[0].UserDefined.Before;
2914 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2915
Mike Stump1eb44332009-09-09 15:08:12 +00002916 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002917 unsigned NumArgsInProto = Proto->getNumArgs();
2918
2919 // (C++ 13.3.2p2): A candidate function having fewer than m
2920 // parameters is viable only if it has an ellipsis in its parameter
2921 // list (8.3.5).
2922 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2923 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002924 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002925 return;
2926 }
2927
2928 // Function types don't have any default arguments, so just check if
2929 // we have enough arguments.
2930 if (NumArgs < NumArgsInProto) {
2931 // Not enough arguments.
2932 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002933 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002934 return;
2935 }
2936
2937 // Determine the implicit conversion sequences for each of the
2938 // arguments.
2939 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2940 if (ArgIdx < NumArgsInProto) {
2941 // (C++ 13.3.2p3): for F to be a viable function, there shall
2942 // exist for each argument an implicit conversion sequence
2943 // (13.3.3.1) that converts that argument to the corresponding
2944 // parameter of F.
2945 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002946 Candidate.Conversions[ArgIdx + 1]
2947 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002948 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002949 /*ForceRValue=*/false,
2950 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00002951 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002952 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002953 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002954 break;
2955 }
2956 } else {
2957 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2958 // argument for which there is no corresponding parameter is
2959 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00002960 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002961 }
2962 }
2963}
2964
Mike Stump390b4cc2009-05-16 07:39:55 +00002965// FIXME: This will eventually be removed, once we've migrated all of the
2966// operator overloading logic over to the scheme used by binary operators, which
2967// works for template instantiation.
Douglas Gregor063daf62009-03-13 18:40:31 +00002968void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002969 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00002970 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002971 OverloadCandidateSet& CandidateSet,
2972 SourceRange OpRange) {
John McCall6e266892010-01-26 03:27:55 +00002973 UnresolvedSet<16> Fns;
Douglas Gregor063daf62009-03-13 18:40:31 +00002974
2975 QualType T1 = Args[0]->getType();
2976 QualType T2;
2977 if (NumArgs > 1)
2978 T2 = Args[1]->getType();
2979
2980 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002981 if (S)
John McCall6e266892010-01-26 03:27:55 +00002982 LookupOverloadedOperatorName(Op, S, T1, T2, Fns);
2983 AddFunctionCandidates(Fns, Args, NumArgs, CandidateSet, false);
2984 AddArgumentDependentLookupCandidates(OpName, false, Args, NumArgs, 0,
2985 CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00002986 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002987 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00002988}
2989
2990/// \brief Add overload candidates for overloaded operators that are
2991/// member functions.
2992///
2993/// Add the overloaded operator candidates that are member functions
2994/// for the operator Op that was used in an operator expression such
2995/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2996/// CandidateSet will store the added overload candidates. (C++
2997/// [over.match.oper]).
2998void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2999 SourceLocation OpLoc,
3000 Expr **Args, unsigned NumArgs,
3001 OverloadCandidateSet& CandidateSet,
3002 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003003 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3004
3005 // C++ [over.match.oper]p3:
3006 // For a unary operator @ with an operand of a type whose
3007 // cv-unqualified version is T1, and for a binary operator @ with
3008 // a left operand of a type whose cv-unqualified version is T1 and
3009 // a right operand of a type whose cv-unqualified version is T2,
3010 // three sets of candidate functions, designated member
3011 // candidates, non-member candidates and built-in candidates, are
3012 // constructed as follows:
3013 QualType T1 = Args[0]->getType();
3014 QualType T2;
3015 if (NumArgs > 1)
3016 T2 = Args[1]->getType();
3017
3018 // -- If T1 is a class type, the set of member candidates is the
3019 // result of the qualified lookup of T1::operator@
3020 // (13.3.1.1.1); otherwise, the set of member candidates is
3021 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00003022 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003023 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003024 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003025 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003026
John McCalla24dc2e2009-11-17 02:14:36 +00003027 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3028 LookupQualifiedName(Operators, T1Rec->getDecl());
3029 Operators.suppressDiagnostics();
3030
Mike Stump1eb44332009-09-09 15:08:12 +00003031 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003032 OperEnd = Operators.end();
3033 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00003034 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00003035 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00003036 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00003037 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00003038 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003039}
3040
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003041/// AddBuiltinCandidate - Add a candidate for a built-in
3042/// operator. ResultTy and ParamTys are the result and parameter types
3043/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003044/// arguments being passed to the candidate. IsAssignmentOperator
3045/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003046/// operator. NumContextualBoolArguments is the number of arguments
3047/// (at the beginning of the argument list) that will be contextually
3048/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00003049void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003050 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003051 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003052 bool IsAssignmentOperator,
3053 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00003054 // Overload resolution is always an unevaluated context.
3055 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3056
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003057 // Add this candidate
3058 CandidateSet.push_back(OverloadCandidate());
3059 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003060 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003061 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003062 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003063 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003064 Candidate.BuiltinTypes.ResultTy = ResultTy;
3065 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3066 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3067
3068 // Determine the implicit conversion sequences for each of the
3069 // arguments.
3070 Candidate.Viable = true;
3071 Candidate.Conversions.resize(NumArgs);
3072 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003073 // C++ [over.match.oper]p4:
3074 // For the built-in assignment operators, conversions of the
3075 // left operand are restricted as follows:
3076 // -- no temporaries are introduced to hold the left operand, and
3077 // -- no user-defined conversions are applied to the left
3078 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00003079 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003080 //
3081 // We block these conversions by turning off user-defined
3082 // conversions, since that is the only way that initialization of
3083 // a reference to a non-class type can occur from something that
3084 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003085 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00003086 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003087 "Contextual conversion to bool requires bool type");
3088 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3089 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003090 Candidate.Conversions[ArgIdx]
3091 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00003092 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003093 /*ForceRValue=*/false,
3094 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003095 }
John McCall1d318332010-01-12 00:44:57 +00003096 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003097 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003098 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003099 break;
3100 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003101 }
3102}
3103
3104/// BuiltinCandidateTypeSet - A set of types that will be used for the
3105/// candidate operator functions for built-in operators (C++
3106/// [over.built]). The types are separated into pointer types and
3107/// enumeration types.
3108class BuiltinCandidateTypeSet {
3109 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003110 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003111
3112 /// PointerTypes - The set of pointer types that will be used in the
3113 /// built-in candidates.
3114 TypeSet PointerTypes;
3115
Sebastian Redl78eb8742009-04-19 21:53:20 +00003116 /// MemberPointerTypes - The set of member pointer types that will be
3117 /// used in the built-in candidates.
3118 TypeSet MemberPointerTypes;
3119
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003120 /// EnumerationTypes - The set of enumeration types that will be
3121 /// used in the built-in candidates.
3122 TypeSet EnumerationTypes;
3123
Douglas Gregor5842ba92009-08-24 15:23:48 +00003124 /// Sema - The semantic analysis instance where we are building the
3125 /// candidate type set.
3126 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003127
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003128 /// Context - The AST context in which we will build the type sets.
3129 ASTContext &Context;
3130
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003131 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3132 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00003133 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003134
3135public:
3136 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003137 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003138
Mike Stump1eb44332009-09-09 15:08:12 +00003139 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00003140 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003141
Douglas Gregor573d9c32009-10-21 23:19:44 +00003142 void AddTypesConvertedFrom(QualType Ty,
3143 SourceLocation Loc,
3144 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003145 bool AllowExplicitConversions,
3146 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003147
3148 /// pointer_begin - First pointer type found;
3149 iterator pointer_begin() { return PointerTypes.begin(); }
3150
Sebastian Redl78eb8742009-04-19 21:53:20 +00003151 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003152 iterator pointer_end() { return PointerTypes.end(); }
3153
Sebastian Redl78eb8742009-04-19 21:53:20 +00003154 /// member_pointer_begin - First member pointer type found;
3155 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3156
3157 /// member_pointer_end - Past the last member pointer type found;
3158 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3159
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003160 /// enumeration_begin - First enumeration type found;
3161 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3162
Sebastian Redl78eb8742009-04-19 21:53:20 +00003163 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003164 iterator enumeration_end() { return EnumerationTypes.end(); }
3165};
3166
Sebastian Redl78eb8742009-04-19 21:53:20 +00003167/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003168/// the set of pointer types along with any more-qualified variants of
3169/// that type. For example, if @p Ty is "int const *", this routine
3170/// will add "int const *", "int const volatile *", "int const
3171/// restrict *", and "int const volatile restrict *" to the set of
3172/// pointer types. Returns true if the add of @p Ty itself succeeded,
3173/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003174///
3175/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003176bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00003177BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3178 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00003179
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003180 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003181 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003182 return false;
3183
John McCall0953e762009-09-24 19:53:00 +00003184 const PointerType *PointerTy = Ty->getAs<PointerType>();
3185 assert(PointerTy && "type was not a pointer type!");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003186
John McCall0953e762009-09-24 19:53:00 +00003187 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003188 // Don't add qualified variants of arrays. For one, they're not allowed
3189 // (the qualifier would sink to the element type), and for another, the
3190 // only overload situation where it matters is subscript or pointer +- int,
3191 // and those shouldn't have qualifier variants anyway.
3192 if (PointeeTy->isArrayType())
3193 return true;
John McCall0953e762009-09-24 19:53:00 +00003194 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00003195 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00003196 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003197 bool hasVolatile = VisibleQuals.hasVolatile();
3198 bool hasRestrict = VisibleQuals.hasRestrict();
3199
John McCall0953e762009-09-24 19:53:00 +00003200 // Iterate through all strict supersets of BaseCVR.
3201 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3202 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003203 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3204 // in the types.
3205 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3206 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00003207 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3208 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003209 }
3210
3211 return true;
3212}
3213
Sebastian Redl78eb8742009-04-19 21:53:20 +00003214/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3215/// to the set of pointer types along with any more-qualified variants of
3216/// that type. For example, if @p Ty is "int const *", this routine
3217/// will add "int const *", "int const volatile *", "int const
3218/// restrict *", and "int const volatile restrict *" to the set of
3219/// pointer types. Returns true if the add of @p Ty itself succeeded,
3220/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003221///
3222/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003223bool
3224BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3225 QualType Ty) {
3226 // Insert this type.
3227 if (!MemberPointerTypes.insert(Ty))
3228 return false;
3229
John McCall0953e762009-09-24 19:53:00 +00003230 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3231 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00003232
John McCall0953e762009-09-24 19:53:00 +00003233 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003234 // Don't add qualified variants of arrays. For one, they're not allowed
3235 // (the qualifier would sink to the element type), and for another, the
3236 // only overload situation where it matters is subscript or pointer +- int,
3237 // and those shouldn't have qualifier variants anyway.
3238 if (PointeeTy->isArrayType())
3239 return true;
John McCall0953e762009-09-24 19:53:00 +00003240 const Type *ClassTy = PointerTy->getClass();
3241
3242 // Iterate through all strict supersets of the pointee type's CVR
3243 // qualifiers.
3244 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3245 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3246 if ((CVR | BaseCVR) != CVR) continue;
3247
3248 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3249 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00003250 }
3251
3252 return true;
3253}
3254
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003255/// AddTypesConvertedFrom - Add each of the types to which the type @p
3256/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00003257/// primarily interested in pointer types and enumeration types. We also
3258/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003259/// AllowUserConversions is true if we should look at the conversion
3260/// functions of a class type, and AllowExplicitConversions if we
3261/// should also include the explicit conversion functions of a class
3262/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003263void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003264BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003265 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003266 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003267 bool AllowExplicitConversions,
3268 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003269 // Only deal with canonical types.
3270 Ty = Context.getCanonicalType(Ty);
3271
3272 // Look through reference types; they aren't part of the type of an
3273 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00003274 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003275 Ty = RefTy->getPointeeType();
3276
3277 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003278 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003279
Sebastian Redla65b5512009-11-05 16:36:20 +00003280 // If we're dealing with an array type, decay to the pointer.
3281 if (Ty->isArrayType())
3282 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3283
Ted Kremenek6217b802009-07-29 21:53:49 +00003284 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003285 QualType PointeeTy = PointerTy->getPointeeType();
3286
3287 // Insert our type, and its more-qualified variants, into the set
3288 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003289 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003290 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00003291 } else if (Ty->isMemberPointerType()) {
3292 // Member pointers are far easier, since the pointee can't be converted.
3293 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3294 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003295 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00003296 EnumerationTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003297 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003298 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003299 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003300 // No conversion functions in incomplete types.
3301 return;
3302 }
Mike Stump1eb44332009-09-09 15:08:12 +00003303
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003304 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00003305 const UnresolvedSetImpl *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00003306 = ClassDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003307 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003308 E = Conversions->end(); I != E; ++I) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003309
Mike Stump1eb44332009-09-09 15:08:12 +00003310 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003311 // about which builtin types we can convert to.
John McCallba135432009-11-21 08:51:07 +00003312 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003313 continue;
3314
John McCallba135432009-11-21 08:51:07 +00003315 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003316 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003317 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003318 VisibleQuals);
3319 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003320 }
3321 }
3322 }
3323}
3324
Douglas Gregor19b7b152009-08-24 13:43:27 +00003325/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3326/// the volatile- and non-volatile-qualified assignment operators for the
3327/// given type to the candidate set.
3328static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3329 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00003330 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003331 unsigned NumArgs,
3332 OverloadCandidateSet &CandidateSet) {
3333 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00003334
Douglas Gregor19b7b152009-08-24 13:43:27 +00003335 // T& operator=(T&, T)
3336 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3337 ParamTypes[1] = T;
3338 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3339 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003340
Douglas Gregor19b7b152009-08-24 13:43:27 +00003341 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3342 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00003343 ParamTypes[0]
3344 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00003345 ParamTypes[1] = T;
3346 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00003347 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003348 }
3349}
Mike Stump1eb44332009-09-09 15:08:12 +00003350
Sebastian Redl9994a342009-10-25 17:03:50 +00003351/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3352/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003353static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3354 Qualifiers VRQuals;
3355 const RecordType *TyRec;
3356 if (const MemberPointerType *RHSMPType =
3357 ArgExpr->getType()->getAs<MemberPointerType>())
3358 TyRec = cast<RecordType>(RHSMPType->getClass());
3359 else
3360 TyRec = ArgExpr->getType()->getAs<RecordType>();
3361 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003362 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003363 VRQuals.addVolatile();
3364 VRQuals.addRestrict();
3365 return VRQuals;
3366 }
3367
3368 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00003369 if (!ClassDecl->hasDefinition())
3370 return VRQuals;
3371
John McCalleec51cf2010-01-20 00:46:10 +00003372 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00003373 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003374
John McCalleec51cf2010-01-20 00:46:10 +00003375 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003376 E = Conversions->end(); I != E; ++I) {
3377 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003378 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3379 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3380 CanTy = ResTypeRef->getPointeeType();
3381 // Need to go down the pointer/mempointer chain and add qualifiers
3382 // as see them.
3383 bool done = false;
3384 while (!done) {
3385 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3386 CanTy = ResTypePtr->getPointeeType();
3387 else if (const MemberPointerType *ResTypeMPtr =
3388 CanTy->getAs<MemberPointerType>())
3389 CanTy = ResTypeMPtr->getPointeeType();
3390 else
3391 done = true;
3392 if (CanTy.isVolatileQualified())
3393 VRQuals.addVolatile();
3394 if (CanTy.isRestrictQualified())
3395 VRQuals.addRestrict();
3396 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3397 return VRQuals;
3398 }
3399 }
3400 }
3401 return VRQuals;
3402}
3403
Douglas Gregor74253732008-11-19 15:42:04 +00003404/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3405/// operator overloads to the candidate set (C++ [over.built]), based
3406/// on the operator @p Op and the arguments given. For example, if the
3407/// operator is a binary '+', this routine might add "int
3408/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003409void
Mike Stump1eb44332009-09-09 15:08:12 +00003410Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003411 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00003412 Expr **Args, unsigned NumArgs,
3413 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003414 // The set of "promoted arithmetic types", which are the arithmetic
3415 // types are that preserved by promotion (C++ [over.built]p2). Note
3416 // that the first few of these types are the promoted integral
3417 // types; these types need to be first.
3418 // FIXME: What about complex?
3419 const unsigned FirstIntegralType = 0;
3420 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00003421 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003422 LastPromotedIntegralType = 13;
3423 const unsigned FirstPromotedArithmeticType = 7,
3424 LastPromotedArithmeticType = 16;
3425 const unsigned NumArithmeticTypes = 16;
3426 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00003427 Context.BoolTy, Context.CharTy, Context.WCharTy,
3428// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003429 Context.SignedCharTy, Context.ShortTy,
3430 Context.UnsignedCharTy, Context.UnsignedShortTy,
3431 Context.IntTy, Context.LongTy, Context.LongLongTy,
3432 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3433 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3434 };
Douglas Gregor652371a2009-10-21 22:01:30 +00003435 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3436 "Invalid first promoted integral type");
3437 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3438 == Context.UnsignedLongLongTy &&
3439 "Invalid last promoted integral type");
3440 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3441 "Invalid first promoted arithmetic type");
3442 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3443 == Context.LongDoubleTy &&
3444 "Invalid last promoted arithmetic type");
3445
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003446 // Find all of the types that the arguments can convert to, but only
3447 // if the operator we're looking at has built-in operator candidates
3448 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003449 Qualifiers VisibleTypeConversionsQuals;
3450 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003451 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3452 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3453
Douglas Gregor5842ba92009-08-24 15:23:48 +00003454 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003455 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3456 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00003457 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003458 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00003459 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003460 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor74253732008-11-19 15:42:04 +00003461 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003462 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregor573d9c32009-10-21 23:19:44 +00003463 OpLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003464 true,
3465 (Op == OO_Exclaim ||
3466 Op == OO_AmpAmp ||
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003467 Op == OO_PipePipe),
3468 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003469 }
3470
3471 bool isComparison = false;
3472 switch (Op) {
3473 case OO_None:
3474 case NUM_OVERLOADED_OPERATORS:
3475 assert(false && "Expected an overloaded operator");
3476 break;
3477
Douglas Gregor74253732008-11-19 15:42:04 +00003478 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00003479 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00003480 goto UnaryStar;
3481 else
3482 goto BinaryStar;
3483 break;
3484
3485 case OO_Plus: // '+' is either unary or binary
3486 if (NumArgs == 1)
3487 goto UnaryPlus;
3488 else
3489 goto BinaryPlus;
3490 break;
3491
3492 case OO_Minus: // '-' is either unary or binary
3493 if (NumArgs == 1)
3494 goto UnaryMinus;
3495 else
3496 goto BinaryMinus;
3497 break;
3498
3499 case OO_Amp: // '&' is either unary or binary
3500 if (NumArgs == 1)
3501 goto UnaryAmp;
3502 else
3503 goto BinaryAmp;
3504
3505 case OO_PlusPlus:
3506 case OO_MinusMinus:
3507 // C++ [over.built]p3:
3508 //
3509 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3510 // is either volatile or empty, there exist candidate operator
3511 // functions of the form
3512 //
3513 // VQ T& operator++(VQ T&);
3514 // T operator++(VQ T&, int);
3515 //
3516 // C++ [over.built]p4:
3517 //
3518 // For every pair (T, VQ), where T is an arithmetic type other
3519 // than bool, and VQ is either volatile or empty, there exist
3520 // candidate operator functions of the form
3521 //
3522 // VQ T& operator--(VQ T&);
3523 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00003524 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00003525 Arith < NumArithmeticTypes; ++Arith) {
3526 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00003527 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003528 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00003529
3530 // Non-volatile version.
3531 if (NumArgs == 1)
3532 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3533 else
3534 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003535 // heuristic to reduce number of builtin candidates in the set.
3536 // Add volatile version only if there are conversions to a volatile type.
3537 if (VisibleTypeConversionsQuals.hasVolatile()) {
3538 // Volatile version
3539 ParamTypes[0]
3540 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3541 if (NumArgs == 1)
3542 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3543 else
3544 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3545 }
Douglas Gregor74253732008-11-19 15:42:04 +00003546 }
3547
3548 // C++ [over.built]p5:
3549 //
3550 // For every pair (T, VQ), where T is a cv-qualified or
3551 // cv-unqualified object type, and VQ is either volatile or
3552 // empty, there exist candidate operator functions of the form
3553 //
3554 // T*VQ& operator++(T*VQ&);
3555 // T*VQ& operator--(T*VQ&);
3556 // T* operator++(T*VQ&, int);
3557 // T* operator--(T*VQ&, int);
3558 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3559 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3560 // Skip pointer types that aren't pointers to object types.
Ted Kremenek6217b802009-07-29 21:53:49 +00003561 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00003562 continue;
3563
Mike Stump1eb44332009-09-09 15:08:12 +00003564 QualType ParamTypes[2] = {
3565 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00003566 };
Mike Stump1eb44332009-09-09 15:08:12 +00003567
Douglas Gregor74253732008-11-19 15:42:04 +00003568 // Without volatile
3569 if (NumArgs == 1)
3570 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3571 else
3572 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3573
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003574 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3575 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003576 // With volatile
John McCall0953e762009-09-24 19:53:00 +00003577 ParamTypes[0]
3578 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00003579 if (NumArgs == 1)
3580 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3581 else
3582 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3583 }
3584 }
3585 break;
3586
3587 UnaryStar:
3588 // C++ [over.built]p6:
3589 // For every cv-qualified or cv-unqualified object type T, there
3590 // exist candidate operator functions of the form
3591 //
3592 // T& operator*(T*);
3593 //
3594 // C++ [over.built]p7:
3595 // For every function type T, there exist candidate operator
3596 // functions of the form
3597 // T& operator*(T*);
3598 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3599 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3600 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00003601 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003602 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00003603 &ParamTy, Args, 1, CandidateSet);
3604 }
3605 break;
3606
3607 UnaryPlus:
3608 // C++ [over.built]p8:
3609 // For every type T, there exist candidate operator functions of
3610 // the form
3611 //
3612 // T* operator+(T*);
3613 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3614 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3615 QualType ParamTy = *Ptr;
3616 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3617 }
Mike Stump1eb44332009-09-09 15:08:12 +00003618
Douglas Gregor74253732008-11-19 15:42:04 +00003619 // Fall through
3620
3621 UnaryMinus:
3622 // C++ [over.built]p9:
3623 // For every promoted arithmetic type T, there exist candidate
3624 // operator functions of the form
3625 //
3626 // T operator+(T);
3627 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003628 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00003629 Arith < LastPromotedArithmeticType; ++Arith) {
3630 QualType ArithTy = ArithmeticTypes[Arith];
3631 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3632 }
3633 break;
3634
3635 case OO_Tilde:
3636 // C++ [over.built]p10:
3637 // For every promoted integral type T, there exist candidate
3638 // operator functions of the form
3639 //
3640 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003641 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00003642 Int < LastPromotedIntegralType; ++Int) {
3643 QualType IntTy = ArithmeticTypes[Int];
3644 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3645 }
3646 break;
3647
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003648 case OO_New:
3649 case OO_Delete:
3650 case OO_Array_New:
3651 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003652 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00003653 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003654 break;
3655
3656 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00003657 UnaryAmp:
3658 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003659 // C++ [over.match.oper]p3:
3660 // -- For the operator ',', the unary operator '&', or the
3661 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003662 break;
3663
Douglas Gregor19b7b152009-08-24 13:43:27 +00003664 case OO_EqualEqual:
3665 case OO_ExclaimEqual:
3666 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00003667 // For every pointer to member type T, there exist candidate operator
3668 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00003669 //
3670 // bool operator==(T,T);
3671 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00003672 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00003673 MemPtr = CandidateTypes.member_pointer_begin(),
3674 MemPtrEnd = CandidateTypes.member_pointer_end();
3675 MemPtr != MemPtrEnd;
3676 ++MemPtr) {
3677 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3678 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3679 }
Mike Stump1eb44332009-09-09 15:08:12 +00003680
Douglas Gregor19b7b152009-08-24 13:43:27 +00003681 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00003682
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003683 case OO_Less:
3684 case OO_Greater:
3685 case OO_LessEqual:
3686 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003687 // C++ [over.built]p15:
3688 //
3689 // For every pointer or enumeration type T, there exist
3690 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003691 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003692 // bool operator<(T, T);
3693 // bool operator>(T, T);
3694 // bool operator<=(T, T);
3695 // bool operator>=(T, T);
3696 // bool operator==(T, T);
3697 // bool operator!=(T, T);
3698 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3699 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3700 QualType ParamTypes[2] = { *Ptr, *Ptr };
3701 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3702 }
Mike Stump1eb44332009-09-09 15:08:12 +00003703 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003704 = CandidateTypes.enumeration_begin();
3705 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3706 QualType ParamTypes[2] = { *Enum, *Enum };
3707 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3708 }
3709
3710 // Fall through.
3711 isComparison = true;
3712
Douglas Gregor74253732008-11-19 15:42:04 +00003713 BinaryPlus:
3714 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003715 if (!isComparison) {
3716 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3717
3718 // C++ [over.built]p13:
3719 //
3720 // For every cv-qualified or cv-unqualified object type T
3721 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003722 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003723 // T* operator+(T*, ptrdiff_t);
3724 // T& operator[](T*, ptrdiff_t); [BELOW]
3725 // T* operator-(T*, ptrdiff_t);
3726 // T* operator+(ptrdiff_t, T*);
3727 // T& operator[](ptrdiff_t, T*); [BELOW]
3728 //
3729 // C++ [over.built]p14:
3730 //
3731 // For every T, where T is a pointer to object type, there
3732 // exist candidate operator functions of the form
3733 //
3734 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00003735 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003736 = CandidateTypes.pointer_begin();
3737 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3738 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3739
3740 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3741 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3742
3743 if (Op == OO_Plus) {
3744 // T* operator+(ptrdiff_t, T*);
3745 ParamTypes[0] = ParamTypes[1];
3746 ParamTypes[1] = *Ptr;
3747 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3748 } else {
3749 // ptrdiff_t operator-(T, T);
3750 ParamTypes[1] = *Ptr;
3751 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3752 Args, 2, CandidateSet);
3753 }
3754 }
3755 }
3756 // Fall through
3757
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003758 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00003759 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003760 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003761 // C++ [over.built]p12:
3762 //
3763 // For every pair of promoted arithmetic types L and R, there
3764 // exist candidate operator functions of the form
3765 //
3766 // LR operator*(L, R);
3767 // LR operator/(L, R);
3768 // LR operator+(L, R);
3769 // LR operator-(L, R);
3770 // bool operator<(L, R);
3771 // bool operator>(L, R);
3772 // bool operator<=(L, R);
3773 // bool operator>=(L, R);
3774 // bool operator==(L, R);
3775 // bool operator!=(L, R);
3776 //
3777 // where LR is the result of the usual arithmetic conversions
3778 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003779 //
3780 // C++ [over.built]p24:
3781 //
3782 // For every pair of promoted arithmetic types L and R, there exist
3783 // candidate operator functions of the form
3784 //
3785 // LR operator?(bool, L, R);
3786 //
3787 // where LR is the result of the usual arithmetic conversions
3788 // between types L and R.
3789 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003790 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003791 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003792 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003793 Right < LastPromotedArithmeticType; ++Right) {
3794 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00003795 QualType Result
3796 = isComparison
3797 ? Context.BoolTy
3798 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003799 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3800 }
3801 }
3802 break;
3803
3804 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00003805 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003806 case OO_Caret:
3807 case OO_Pipe:
3808 case OO_LessLess:
3809 case OO_GreaterGreater:
3810 // C++ [over.built]p17:
3811 //
3812 // For every pair of promoted integral types L and R, there
3813 // exist candidate operator functions of the form
3814 //
3815 // LR operator%(L, R);
3816 // LR operator&(L, R);
3817 // LR operator^(L, R);
3818 // LR operator|(L, R);
3819 // L operator<<(L, R);
3820 // L operator>>(L, R);
3821 //
3822 // where LR is the result of the usual arithmetic conversions
3823 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00003824 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003825 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003826 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003827 Right < LastPromotedIntegralType; ++Right) {
3828 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3829 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3830 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00003831 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003832 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3833 }
3834 }
3835 break;
3836
3837 case OO_Equal:
3838 // C++ [over.built]p20:
3839 //
3840 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00003841 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003842 // empty, there exist candidate operator functions of the form
3843 //
3844 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003845 for (BuiltinCandidateTypeSet::iterator
3846 Enum = CandidateTypes.enumeration_begin(),
3847 EnumEnd = CandidateTypes.enumeration_end();
3848 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00003849 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003850 CandidateSet);
3851 for (BuiltinCandidateTypeSet::iterator
3852 MemPtr = CandidateTypes.member_pointer_begin(),
3853 MemPtrEnd = CandidateTypes.member_pointer_end();
3854 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00003855 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003856 CandidateSet);
3857 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003858
3859 case OO_PlusEqual:
3860 case OO_MinusEqual:
3861 // C++ [over.built]p19:
3862 //
3863 // For every pair (T, VQ), where T is any type and VQ is either
3864 // volatile or empty, there exist candidate operator functions
3865 // of the form
3866 //
3867 // T*VQ& operator=(T*VQ&, T*);
3868 //
3869 // C++ [over.built]p21:
3870 //
3871 // For every pair (T, VQ), where T is a cv-qualified or
3872 // cv-unqualified object type and VQ is either volatile or
3873 // empty, there exist candidate operator functions of the form
3874 //
3875 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3876 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3877 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3878 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3879 QualType ParamTypes[2];
3880 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3881
3882 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003883 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003884 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3885 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003886
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003887 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3888 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003889 // volatile version
John McCall0953e762009-09-24 19:53:00 +00003890 ParamTypes[0]
3891 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003892 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3893 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003894 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003895 }
3896 // Fall through.
3897
3898 case OO_StarEqual:
3899 case OO_SlashEqual:
3900 // C++ [over.built]p18:
3901 //
3902 // For every triple (L, VQ, R), where L is an arithmetic type,
3903 // VQ is either volatile or empty, and R is a promoted
3904 // arithmetic type, there exist candidate operator functions of
3905 // the form
3906 //
3907 // VQ L& operator=(VQ L&, R);
3908 // VQ L& operator*=(VQ L&, R);
3909 // VQ L& operator/=(VQ L&, R);
3910 // VQ L& operator+=(VQ L&, R);
3911 // VQ L& operator-=(VQ L&, R);
3912 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003913 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003914 Right < LastPromotedArithmeticType; ++Right) {
3915 QualType ParamTypes[2];
3916 ParamTypes[1] = ArithmeticTypes[Right];
3917
3918 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003919 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003920 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3921 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003922
3923 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003924 if (VisibleTypeConversionsQuals.hasVolatile()) {
3925 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3926 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3927 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3928 /*IsAssigmentOperator=*/Op == OO_Equal);
3929 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003930 }
3931 }
3932 break;
3933
3934 case OO_PercentEqual:
3935 case OO_LessLessEqual:
3936 case OO_GreaterGreaterEqual:
3937 case OO_AmpEqual:
3938 case OO_CaretEqual:
3939 case OO_PipeEqual:
3940 // C++ [over.built]p22:
3941 //
3942 // For every triple (L, VQ, R), where L is an integral type, VQ
3943 // is either volatile or empty, and R is a promoted integral
3944 // type, there exist candidate operator functions of the form
3945 //
3946 // VQ L& operator%=(VQ L&, R);
3947 // VQ L& operator<<=(VQ L&, R);
3948 // VQ L& operator>>=(VQ L&, R);
3949 // VQ L& operator&=(VQ L&, R);
3950 // VQ L& operator^=(VQ L&, R);
3951 // VQ L& operator|=(VQ L&, R);
3952 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003953 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003954 Right < LastPromotedIntegralType; ++Right) {
3955 QualType ParamTypes[2];
3956 ParamTypes[1] = ArithmeticTypes[Right];
3957
3958 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003959 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003960 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00003961 if (VisibleTypeConversionsQuals.hasVolatile()) {
3962 // Add this built-in operator as a candidate (VQ is 'volatile').
3963 ParamTypes[0] = ArithmeticTypes[Left];
3964 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3965 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3966 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3967 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003968 }
3969 }
3970 break;
3971
Douglas Gregor74253732008-11-19 15:42:04 +00003972 case OO_Exclaim: {
3973 // C++ [over.operator]p23:
3974 //
3975 // There also exist candidate operator functions of the form
3976 //
Mike Stump1eb44332009-09-09 15:08:12 +00003977 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00003978 // bool operator&&(bool, bool); [BELOW]
3979 // bool operator||(bool, bool); [BELOW]
3980 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003981 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3982 /*IsAssignmentOperator=*/false,
3983 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00003984 break;
3985 }
3986
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003987 case OO_AmpAmp:
3988 case OO_PipePipe: {
3989 // C++ [over.operator]p23:
3990 //
3991 // There also exist candidate operator functions of the form
3992 //
Douglas Gregor74253732008-11-19 15:42:04 +00003993 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003994 // bool operator&&(bool, bool);
3995 // bool operator||(bool, bool);
3996 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003997 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3998 /*IsAssignmentOperator=*/false,
3999 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004000 break;
4001 }
4002
4003 case OO_Subscript:
4004 // C++ [over.built]p13:
4005 //
4006 // For every cv-qualified or cv-unqualified object type T there
4007 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004008 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004009 // T* operator+(T*, ptrdiff_t); [ABOVE]
4010 // T& operator[](T*, ptrdiff_t);
4011 // T* operator-(T*, ptrdiff_t); [ABOVE]
4012 // T* operator+(ptrdiff_t, T*); [ABOVE]
4013 // T& operator[](ptrdiff_t, T*);
4014 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4015 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4016 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00004017 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004018 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004019
4020 // T& operator[](T*, ptrdiff_t)
4021 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4022
4023 // T& operator[](ptrdiff_t, T*);
4024 ParamTypes[0] = ParamTypes[1];
4025 ParamTypes[1] = *Ptr;
4026 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4027 }
4028 break;
4029
4030 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004031 // C++ [over.built]p11:
4032 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4033 // C1 is the same type as C2 or is a derived class of C2, T is an object
4034 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4035 // there exist candidate operator functions of the form
4036 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4037 // where CV12 is the union of CV1 and CV2.
4038 {
4039 for (BuiltinCandidateTypeSet::iterator Ptr =
4040 CandidateTypes.pointer_begin();
4041 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4042 QualType C1Ty = (*Ptr);
4043 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004044 QualifierCollector Q1;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004045 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004046 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004047 if (!isa<RecordType>(C1))
4048 continue;
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004049 // heuristic to reduce number of builtin candidates in the set.
4050 // Add volatile/restrict version only if there are conversions to a
4051 // volatile/restrict type.
4052 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4053 continue;
4054 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4055 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004056 }
4057 for (BuiltinCandidateTypeSet::iterator
4058 MemPtr = CandidateTypes.member_pointer_begin(),
4059 MemPtrEnd = CandidateTypes.member_pointer_end();
4060 MemPtr != MemPtrEnd; ++MemPtr) {
4061 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4062 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00004063 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004064 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4065 break;
4066 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4067 // build CV12 T&
4068 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004069 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4070 T.isVolatileQualified())
4071 continue;
4072 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4073 T.isRestrictQualified())
4074 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004075 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004076 QualType ResultTy = Context.getLValueReferenceType(T);
4077 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4078 }
4079 }
4080 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004081 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004082
4083 case OO_Conditional:
4084 // Note that we don't consider the first argument, since it has been
4085 // contextually converted to bool long ago. The candidates below are
4086 // therefore added as binary.
4087 //
4088 // C++ [over.built]p24:
4089 // For every type T, where T is a pointer or pointer-to-member type,
4090 // there exist candidate operator functions of the form
4091 //
4092 // T operator?(bool, T, T);
4093 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004094 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4095 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4096 QualType ParamTypes[2] = { *Ptr, *Ptr };
4097 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4098 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00004099 for (BuiltinCandidateTypeSet::iterator Ptr =
4100 CandidateTypes.member_pointer_begin(),
4101 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4102 QualType ParamTypes[2] = { *Ptr, *Ptr };
4103 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4104 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004105 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004106 }
4107}
4108
Douglas Gregorfa047642009-02-04 00:32:51 +00004109/// \brief Add function candidates found via argument-dependent lookup
4110/// to the set of overloading candidates.
4111///
4112/// This routine performs argument-dependent name lookup based on the
4113/// given function name (which may also be an operator name) and adds
4114/// all of the overload candidates found by ADL to the overload
4115/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00004116void
Douglas Gregorfa047642009-02-04 00:32:51 +00004117Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00004118 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00004119 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00004120 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004121 OverloadCandidateSet& CandidateSet,
4122 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00004123 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00004124
John McCalla113e722010-01-26 06:04:06 +00004125 // FIXME: This approach for uniquing ADL results (and removing
4126 // redundant candidates from the set) relies on pointer-equality,
4127 // which means we need to key off the canonical decl. However,
4128 // always going back to the canonical decl might not get us the
4129 // right set of default arguments. What default arguments are
4130 // we supposed to consider on ADL candidates, anyway?
4131
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004132 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00004133 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00004134
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004135 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004136 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4137 CandEnd = CandidateSet.end();
4138 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00004139 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00004140 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00004141 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00004142 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00004143 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004144
4145 // For each of the ADL candidates we found, add it to the overload
4146 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00004147 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00004148 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00004149 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00004150 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004151 continue;
4152
John McCall9aa472c2010-03-19 07:35:19 +00004153 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004154 false, false, PartialOverloading);
4155 } else
John McCall6e266892010-01-26 03:27:55 +00004156 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00004157 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004158 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00004159 }
Douglas Gregorfa047642009-02-04 00:32:51 +00004160}
4161
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004162/// isBetterOverloadCandidate - Determines whether the first overload
4163/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00004164bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004165Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCall5769d612010-02-08 23:07:23 +00004166 const OverloadCandidate& Cand2,
4167 SourceLocation Loc) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004168 // Define viable functions to be better candidates than non-viable
4169 // functions.
4170 if (!Cand2.Viable)
4171 return Cand1.Viable;
4172 else if (!Cand1.Viable)
4173 return false;
4174
Douglas Gregor88a35142008-12-22 05:46:06 +00004175 // C++ [over.match.best]p1:
4176 //
4177 // -- if F is a static member function, ICS1(F) is defined such
4178 // that ICS1(F) is neither better nor worse than ICS1(G) for
4179 // any function G, and, symmetrically, ICS1(G) is neither
4180 // better nor worse than ICS1(F).
4181 unsigned StartArg = 0;
4182 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4183 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004184
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004185 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00004186 // A viable function F1 is defined to be a better function than another
4187 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004188 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004189 unsigned NumArgs = Cand1.Conversions.size();
4190 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4191 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004192 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004193 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4194 Cand2.Conversions[ArgIdx])) {
4195 case ImplicitConversionSequence::Better:
4196 // Cand1 has a better conversion sequence.
4197 HasBetterConversion = true;
4198 break;
4199
4200 case ImplicitConversionSequence::Worse:
4201 // Cand1 can't be better than Cand2.
4202 return false;
4203
4204 case ImplicitConversionSequence::Indistinguishable:
4205 // Do nothing.
4206 break;
4207 }
4208 }
4209
Mike Stump1eb44332009-09-09 15:08:12 +00004210 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004211 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004212 if (HasBetterConversion)
4213 return true;
4214
Mike Stump1eb44332009-09-09 15:08:12 +00004215 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004216 // specialization, or, if not that,
4217 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4218 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4219 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004220
4221 // -- F1 and F2 are function template specializations, and the function
4222 // template for F1 is more specialized than the template for F2
4223 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004224 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00004225 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4226 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004227 if (FunctionTemplateDecl *BetterTemplate
4228 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4229 Cand2.Function->getPrimaryTemplate(),
John McCall5769d612010-02-08 23:07:23 +00004230 Loc,
Douglas Gregor5d7d3752009-09-14 23:02:14 +00004231 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4232 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004233 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004234
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004235 // -- the context is an initialization by user-defined conversion
4236 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4237 // from the return type of F1 to the destination type (i.e.,
4238 // the type of the entity being initialized) is a better
4239 // conversion sequence than the standard conversion sequence
4240 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00004241 if (Cand1.Function && Cand2.Function &&
4242 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004243 isa<CXXConversionDecl>(Cand2.Function)) {
4244 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4245 Cand2.FinalConversion)) {
4246 case ImplicitConversionSequence::Better:
4247 // Cand1 has a better conversion sequence.
4248 return true;
4249
4250 case ImplicitConversionSequence::Worse:
4251 // Cand1 can't be better than Cand2.
4252 return false;
4253
4254 case ImplicitConversionSequence::Indistinguishable:
4255 // Do nothing
4256 break;
4257 }
4258 }
4259
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004260 return false;
4261}
4262
Mike Stump1eb44332009-09-09 15:08:12 +00004263/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00004264/// within an overload candidate set.
4265///
4266/// \param CandidateSet the set of candidate functions.
4267///
4268/// \param Loc the location of the function name (or operator symbol) for
4269/// which overload resolution occurs.
4270///
Mike Stump1eb44332009-09-09 15:08:12 +00004271/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00004272/// function, Best points to the candidate function found.
4273///
4274/// \returns The result of overload resolution.
Douglas Gregor20093b42009-12-09 23:02:17 +00004275OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4276 SourceLocation Loc,
4277 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004278 // Find the best viable function.
4279 Best = CandidateSet.end();
4280 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4281 Cand != CandidateSet.end(); ++Cand) {
4282 if (Cand->Viable) {
John McCall5769d612010-02-08 23:07:23 +00004283 if (Best == CandidateSet.end() ||
4284 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004285 Best = Cand;
4286 }
4287 }
4288
4289 // If we didn't find any viable functions, abort.
4290 if (Best == CandidateSet.end())
4291 return OR_No_Viable_Function;
4292
4293 // Make sure that this function is better than every other viable
4294 // function. If not, we have an ambiguity.
4295 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4296 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00004297 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004298 Cand != Best &&
John McCall5769d612010-02-08 23:07:23 +00004299 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004300 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004301 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004302 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004303 }
Mike Stump1eb44332009-09-09 15:08:12 +00004304
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004305 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004306 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00004307 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004308 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004309 return OR_Deleted;
4310
Douglas Gregore0762c92009-06-19 23:52:42 +00004311 // C++ [basic.def.odr]p2:
4312 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00004313 // when referred to from a potentially-evaluated expression. [Note: this
4314 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00004315 // (clause 13), user-defined conversions (12.3.2), allocation function for
4316 // placement new (5.3.4), as well as non-default initialization (8.5).
4317 if (Best->Function)
4318 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004319 return OR_Success;
4320}
4321
John McCall3c80f572010-01-12 02:15:36 +00004322namespace {
4323
4324enum OverloadCandidateKind {
4325 oc_function,
4326 oc_method,
4327 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00004328 oc_function_template,
4329 oc_method_template,
4330 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00004331 oc_implicit_default_constructor,
4332 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00004333 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00004334};
4335
John McCall220ccbf2010-01-13 00:25:19 +00004336OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4337 FunctionDecl *Fn,
4338 std::string &Description) {
4339 bool isTemplate = false;
4340
4341 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4342 isTemplate = true;
4343 Description = S.getTemplateArgumentBindingsText(
4344 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4345 }
John McCallb1622a12010-01-06 09:43:14 +00004346
4347 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00004348 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00004349 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00004350
John McCall3c80f572010-01-12 02:15:36 +00004351 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4352 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00004353 }
4354
4355 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4356 // This actually gets spelled 'candidate function' for now, but
4357 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00004358 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00004359 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00004360
4361 assert(Meth->isCopyAssignment()
4362 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00004363 return oc_implicit_copy_assignment;
4364 }
4365
John McCall220ccbf2010-01-13 00:25:19 +00004366 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00004367}
4368
4369} // end anonymous namespace
4370
4371// Notes the location of an overload candidate.
4372void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00004373 std::string FnDesc;
4374 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4375 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4376 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00004377}
4378
John McCall1d318332010-01-12 00:44:57 +00004379/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4380/// "lead" diagnostic; it will be given two arguments, the source and
4381/// target types of the conversion.
4382void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4383 SourceLocation CaretLoc,
4384 const PartialDiagnostic &PDiag) {
4385 Diag(CaretLoc, PDiag)
4386 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4387 for (AmbiguousConversionSequence::const_iterator
4388 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4389 NoteOverloadCandidate(*I);
4390 }
John McCall81201622010-01-08 04:41:39 +00004391}
4392
John McCall1d318332010-01-12 00:44:57 +00004393namespace {
4394
John McCalladbb8f82010-01-13 09:16:55 +00004395void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4396 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4397 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00004398 assert(Cand->Function && "for now, candidate must be a function");
4399 FunctionDecl *Fn = Cand->Function;
4400
4401 // There's a conversion slot for the object argument if this is a
4402 // non-constructor method. Note that 'I' corresponds the
4403 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00004404 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00004405 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00004406 if (I == 0)
4407 isObjectArgument = true;
4408 else
4409 I--;
John McCall220ccbf2010-01-13 00:25:19 +00004410 }
4411
John McCall220ccbf2010-01-13 00:25:19 +00004412 std::string FnDesc;
4413 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4414
John McCalladbb8f82010-01-13 09:16:55 +00004415 Expr *FromExpr = Conv.Bad.FromExpr;
4416 QualType FromTy = Conv.Bad.getFromType();
4417 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00004418
John McCall5920dbb2010-02-02 02:42:52 +00004419 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00004420 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00004421 Expr *E = FromExpr->IgnoreParens();
4422 if (isa<UnaryOperator>(E))
4423 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00004424 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00004425
4426 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
4427 << (unsigned) FnKind << FnDesc
4428 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4429 << ToTy << Name << I+1;
4430 return;
4431 }
4432
John McCall258b2032010-01-23 08:10:49 +00004433 // Do some hand-waving analysis to see if the non-viability is due
4434 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00004435 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4436 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4437 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4438 CToTy = RT->getPointeeType();
4439 else {
4440 // TODO: detect and diagnose the full richness of const mismatches.
4441 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4442 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4443 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4444 }
4445
4446 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4447 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4448 // It is dumb that we have to do this here.
4449 while (isa<ArrayType>(CFromTy))
4450 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4451 while (isa<ArrayType>(CToTy))
4452 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4453
4454 Qualifiers FromQs = CFromTy.getQualifiers();
4455 Qualifiers ToQs = CToTy.getQualifiers();
4456
4457 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4458 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4459 << (unsigned) FnKind << FnDesc
4460 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4461 << FromTy
4462 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4463 << (unsigned) isObjectArgument << I+1;
4464 return;
4465 }
4466
4467 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4468 assert(CVR && "unexpected qualifiers mismatch");
4469
4470 if (isObjectArgument) {
4471 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4472 << (unsigned) FnKind << FnDesc
4473 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4474 << FromTy << (CVR - 1);
4475 } else {
4476 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4477 << (unsigned) FnKind << FnDesc
4478 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4479 << FromTy << (CVR - 1) << I+1;
4480 }
4481 return;
4482 }
4483
John McCall258b2032010-01-23 08:10:49 +00004484 // Diagnose references or pointers to incomplete types differently,
4485 // since it's far from impossible that the incompleteness triggered
4486 // the failure.
4487 QualType TempFromTy = FromTy.getNonReferenceType();
4488 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
4489 TempFromTy = PTy->getPointeeType();
4490 if (TempFromTy->isIncompleteType()) {
4491 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
4492 << (unsigned) FnKind << FnDesc
4493 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4494 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4495 return;
4496 }
4497
John McCall651f3ee2010-01-14 03:28:57 +00004498 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00004499 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4500 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00004501 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00004502 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00004503}
4504
4505void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4506 unsigned NumFormalArgs) {
4507 // TODO: treat calls to a missing default constructor as a special case
4508
4509 FunctionDecl *Fn = Cand->Function;
4510 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4511
4512 unsigned MinParams = Fn->getMinRequiredArguments();
4513
4514 // at least / at most / exactly
4515 unsigned mode, modeCount;
4516 if (NumFormalArgs < MinParams) {
4517 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4518 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4519 mode = 0; // "at least"
4520 else
4521 mode = 2; // "exactly"
4522 modeCount = MinParams;
4523 } else {
4524 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4525 if (MinParams != FnTy->getNumArgs())
4526 mode = 1; // "at most"
4527 else
4528 mode = 2; // "exactly"
4529 modeCount = FnTy->getNumArgs();
4530 }
4531
4532 std::string Description;
4533 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4534
4535 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4536 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00004537}
4538
John McCall342fec42010-02-01 18:53:26 +00004539/// Diagnose a failed template-argument deduction.
4540void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
4541 Expr **Args, unsigned NumArgs) {
4542 FunctionDecl *Fn = Cand->Function; // pattern
4543
4544 TemplateParameter Param = TemplateParameter::getFromOpaqueValue(
4545 Cand->DeductionFailure.TemplateParameter);
4546
4547 switch (Cand->DeductionFailure.Result) {
4548 case Sema::TDK_Success:
4549 llvm_unreachable("TDK_success while diagnosing bad deduction");
4550
4551 case Sema::TDK_Incomplete: {
4552 NamedDecl *ParamD;
4553 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
4554 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
4555 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
4556 assert(ParamD && "no parameter found for incomplete deduction result");
4557 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
4558 << ParamD->getDeclName();
4559 return;
4560 }
4561
4562 // TODO: diagnose these individually, then kill off
4563 // note_ovl_candidate_bad_deduction, which is uselessly vague.
4564 case Sema::TDK_InstantiationDepth:
4565 case Sema::TDK_Inconsistent:
4566 case Sema::TDK_InconsistentQuals:
4567 case Sema::TDK_SubstitutionFailure:
4568 case Sema::TDK_NonDeducedMismatch:
4569 case Sema::TDK_TooManyArguments:
4570 case Sema::TDK_TooFewArguments:
4571 case Sema::TDK_InvalidExplicitArguments:
4572 case Sema::TDK_FailedOverloadResolution:
4573 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
4574 return;
4575 }
4576}
4577
4578/// Generates a 'note' diagnostic for an overload candidate. We've
4579/// already generated a primary error at the call site.
4580///
4581/// It really does need to be a single diagnostic with its caret
4582/// pointed at the candidate declaration. Yes, this creates some
4583/// major challenges of technical writing. Yes, this makes pointing
4584/// out problems with specific arguments quite awkward. It's still
4585/// better than generating twenty screens of text for every failed
4586/// overload.
4587///
4588/// It would be great to be able to express per-candidate problems
4589/// more richly for those diagnostic clients that cared, but we'd
4590/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00004591void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4592 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00004593 FunctionDecl *Fn = Cand->Function;
4594
John McCall81201622010-01-08 04:41:39 +00004595 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00004596 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00004597 std::string FnDesc;
4598 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00004599
4600 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00004601 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00004602 return;
John McCall81201622010-01-08 04:41:39 +00004603 }
4604
John McCall220ccbf2010-01-13 00:25:19 +00004605 // We don't really have anything else to say about viable candidates.
4606 if (Cand->Viable) {
4607 S.NoteOverloadCandidate(Fn);
4608 return;
4609 }
John McCall1d318332010-01-12 00:44:57 +00004610
John McCalladbb8f82010-01-13 09:16:55 +00004611 switch (Cand->FailureKind) {
4612 case ovl_fail_too_many_arguments:
4613 case ovl_fail_too_few_arguments:
4614 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00004615
John McCalladbb8f82010-01-13 09:16:55 +00004616 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00004617 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
4618
John McCall717e8912010-01-23 05:17:32 +00004619 case ovl_fail_trivial_conversion:
4620 case ovl_fail_bad_final_conversion:
John McCalladbb8f82010-01-13 09:16:55 +00004621 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00004622
John McCallb1bdc622010-02-25 01:37:24 +00004623 case ovl_fail_bad_conversion: {
4624 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
4625 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00004626 if (Cand->Conversions[I].isBad())
4627 return DiagnoseBadConversion(S, Cand, I);
4628
4629 // FIXME: this currently happens when we're called from SemaInit
4630 // when user-conversion overload fails. Figure out how to handle
4631 // those conditions and diagnose them well.
4632 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00004633 }
John McCallb1bdc622010-02-25 01:37:24 +00004634 }
John McCalla1d7d622010-01-08 00:58:21 +00004635}
4636
4637void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4638 // Desugar the type of the surrogate down to a function type,
4639 // retaining as many typedefs as possible while still showing
4640 // the function type (and, therefore, its parameter types).
4641 QualType FnType = Cand->Surrogate->getConversionType();
4642 bool isLValueReference = false;
4643 bool isRValueReference = false;
4644 bool isPointer = false;
4645 if (const LValueReferenceType *FnTypeRef =
4646 FnType->getAs<LValueReferenceType>()) {
4647 FnType = FnTypeRef->getPointeeType();
4648 isLValueReference = true;
4649 } else if (const RValueReferenceType *FnTypeRef =
4650 FnType->getAs<RValueReferenceType>()) {
4651 FnType = FnTypeRef->getPointeeType();
4652 isRValueReference = true;
4653 }
4654 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4655 FnType = FnTypePtr->getPointeeType();
4656 isPointer = true;
4657 }
4658 // Desugar down to a function type.
4659 FnType = QualType(FnType->getAs<FunctionType>(), 0);
4660 // Reconstruct the pointer/reference as appropriate.
4661 if (isPointer) FnType = S.Context.getPointerType(FnType);
4662 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
4663 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
4664
4665 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
4666 << FnType;
4667}
4668
4669void NoteBuiltinOperatorCandidate(Sema &S,
4670 const char *Opc,
4671 SourceLocation OpLoc,
4672 OverloadCandidate *Cand) {
4673 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
4674 std::string TypeStr("operator");
4675 TypeStr += Opc;
4676 TypeStr += "(";
4677 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4678 if (Cand->Conversions.size() == 1) {
4679 TypeStr += ")";
4680 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
4681 } else {
4682 TypeStr += ", ";
4683 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4684 TypeStr += ")";
4685 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
4686 }
4687}
4688
4689void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
4690 OverloadCandidate *Cand) {
4691 unsigned NoOperands = Cand->Conversions.size();
4692 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4693 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00004694 if (ICS.isBad()) break; // all meaningless after first invalid
4695 if (!ICS.isAmbiguous()) continue;
4696
4697 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004698 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00004699 }
4700}
4701
John McCall1b77e732010-01-15 23:32:50 +00004702SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
4703 if (Cand->Function)
4704 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00004705 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00004706 return Cand->Surrogate->getLocation();
4707 return SourceLocation();
4708}
4709
John McCallbf65c0b2010-01-12 00:48:53 +00004710struct CompareOverloadCandidatesForDisplay {
4711 Sema &S;
4712 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00004713
4714 bool operator()(const OverloadCandidate *L,
4715 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00004716 // Fast-path this check.
4717 if (L == R) return false;
4718
John McCall81201622010-01-08 04:41:39 +00004719 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00004720 if (L->Viable) {
4721 if (!R->Viable) return true;
4722
4723 // TODO: introduce a tri-valued comparison for overload
4724 // candidates. Would be more worthwhile if we had a sort
4725 // that could exploit it.
John McCall5769d612010-02-08 23:07:23 +00004726 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
4727 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00004728 } else if (R->Viable)
4729 return false;
John McCall81201622010-01-08 04:41:39 +00004730
John McCall1b77e732010-01-15 23:32:50 +00004731 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00004732
John McCall1b77e732010-01-15 23:32:50 +00004733 // Criteria by which we can sort non-viable candidates:
4734 if (!L->Viable) {
4735 // 1. Arity mismatches come after other candidates.
4736 if (L->FailureKind == ovl_fail_too_many_arguments ||
4737 L->FailureKind == ovl_fail_too_few_arguments)
4738 return false;
4739 if (R->FailureKind == ovl_fail_too_many_arguments ||
4740 R->FailureKind == ovl_fail_too_few_arguments)
4741 return true;
John McCall81201622010-01-08 04:41:39 +00004742
John McCall717e8912010-01-23 05:17:32 +00004743 // 2. Bad conversions come first and are ordered by the number
4744 // of bad conversions and quality of good conversions.
4745 if (L->FailureKind == ovl_fail_bad_conversion) {
4746 if (R->FailureKind != ovl_fail_bad_conversion)
4747 return true;
4748
4749 // If there's any ordering between the defined conversions...
4750 // FIXME: this might not be transitive.
4751 assert(L->Conversions.size() == R->Conversions.size());
4752
4753 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00004754 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
4755 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall717e8912010-01-23 05:17:32 +00004756 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
4757 R->Conversions[I])) {
4758 case ImplicitConversionSequence::Better:
4759 leftBetter++;
4760 break;
4761
4762 case ImplicitConversionSequence::Worse:
4763 leftBetter--;
4764 break;
4765
4766 case ImplicitConversionSequence::Indistinguishable:
4767 break;
4768 }
4769 }
4770 if (leftBetter > 0) return true;
4771 if (leftBetter < 0) return false;
4772
4773 } else if (R->FailureKind == ovl_fail_bad_conversion)
4774 return false;
4775
John McCall1b77e732010-01-15 23:32:50 +00004776 // TODO: others?
4777 }
4778
4779 // Sort everything else by location.
4780 SourceLocation LLoc = GetLocationForCandidate(L);
4781 SourceLocation RLoc = GetLocationForCandidate(R);
4782
4783 // Put candidates without locations (e.g. builtins) at the end.
4784 if (LLoc.isInvalid()) return false;
4785 if (RLoc.isInvalid()) return true;
4786
4787 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00004788 }
4789};
4790
John McCall717e8912010-01-23 05:17:32 +00004791/// CompleteNonViableCandidate - Normally, overload resolution only
4792/// computes up to the first
4793void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
4794 Expr **Args, unsigned NumArgs) {
4795 assert(!Cand->Viable);
4796
4797 // Don't do anything on failures other than bad conversion.
4798 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
4799
4800 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00004801 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00004802 unsigned ConvCount = Cand->Conversions.size();
4803 while (true) {
4804 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
4805 ConvIdx++;
4806 if (Cand->Conversions[ConvIdx - 1].isBad())
4807 break;
4808 }
4809
4810 if (ConvIdx == ConvCount)
4811 return;
4812
John McCallb1bdc622010-02-25 01:37:24 +00004813 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
4814 "remaining conversion is initialized?");
4815
John McCall717e8912010-01-23 05:17:32 +00004816 // FIXME: these should probably be preserved from the overload
4817 // operation somehow.
4818 bool SuppressUserConversions = false;
4819 bool ForceRValue = false;
4820
4821 const FunctionProtoType* Proto;
4822 unsigned ArgIdx = ConvIdx;
4823
4824 if (Cand->IsSurrogate) {
4825 QualType ConvType
4826 = Cand->Surrogate->getConversionType().getNonReferenceType();
4827 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4828 ConvType = ConvPtrType->getPointeeType();
4829 Proto = ConvType->getAs<FunctionProtoType>();
4830 ArgIdx--;
4831 } else if (Cand->Function) {
4832 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
4833 if (isa<CXXMethodDecl>(Cand->Function) &&
4834 !isa<CXXConstructorDecl>(Cand->Function))
4835 ArgIdx--;
4836 } else {
4837 // Builtin binary operator with a bad first conversion.
4838 assert(ConvCount <= 3);
4839 for (; ConvIdx != ConvCount; ++ConvIdx)
4840 Cand->Conversions[ConvIdx]
4841 = S.TryCopyInitialization(Args[ConvIdx],
4842 Cand->BuiltinTypes.ParamTypes[ConvIdx],
4843 SuppressUserConversions, ForceRValue,
4844 /*InOverloadResolution*/ true);
4845 return;
4846 }
4847
4848 // Fill in the rest of the conversions.
4849 unsigned NumArgsInProto = Proto->getNumArgs();
4850 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
4851 if (ArgIdx < NumArgsInProto)
4852 Cand->Conversions[ConvIdx]
4853 = S.TryCopyInitialization(Args[ArgIdx], Proto->getArgType(ArgIdx),
4854 SuppressUserConversions, ForceRValue,
4855 /*InOverloadResolution=*/true);
4856 else
4857 Cand->Conversions[ConvIdx].setEllipsis();
4858 }
4859}
4860
John McCalla1d7d622010-01-08 00:58:21 +00004861} // end anonymous namespace
4862
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004863/// PrintOverloadCandidates - When overload resolution fails, prints
4864/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00004865/// set.
Mike Stump1eb44332009-09-09 15:08:12 +00004866void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004867Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall81201622010-01-08 04:41:39 +00004868 OverloadCandidateDisplayKind OCD,
John McCallcbce6062010-01-12 07:18:19 +00004869 Expr **Args, unsigned NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004870 const char *Opc,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00004871 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00004872 // Sort the candidates by viability and position. Sorting directly would
4873 // be prohibitive, so we make a set of pointers and sort those.
4874 llvm::SmallVector<OverloadCandidate*, 32> Cands;
4875 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
4876 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4877 LastCand = CandidateSet.end();
John McCall717e8912010-01-23 05:17:32 +00004878 Cand != LastCand; ++Cand) {
4879 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00004880 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00004881 else if (OCD == OCD_AllCandidates) {
4882 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
4883 Cands.push_back(Cand);
4884 }
4885 }
4886
John McCallbf65c0b2010-01-12 00:48:53 +00004887 std::sort(Cands.begin(), Cands.end(),
4888 CompareOverloadCandidatesForDisplay(*this));
John McCall81201622010-01-08 04:41:39 +00004889
John McCall1d318332010-01-12 00:44:57 +00004890 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00004891
John McCall81201622010-01-08 04:41:39 +00004892 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
4893 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
4894 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00004895
John McCalla1d7d622010-01-08 00:58:21 +00004896 if (Cand->Function)
John McCall220ccbf2010-01-13 00:25:19 +00004897 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00004898 else if (Cand->IsSurrogate)
4899 NoteSurrogateCandidate(*this, Cand);
4900
4901 // This a builtin candidate. We do not, in general, want to list
4902 // every possible builtin candidate.
John McCall1d318332010-01-12 00:44:57 +00004903 else if (Cand->Viable) {
4904 // Generally we only see ambiguities including viable builtin
4905 // operators if overload resolution got screwed up by an
4906 // ambiguous user-defined conversion.
4907 //
4908 // FIXME: It's quite possible for different conversions to see
4909 // different ambiguities, though.
4910 if (!ReportedAmbiguousConversions) {
4911 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
4912 ReportedAmbiguousConversions = true;
4913 }
John McCalla1d7d622010-01-08 00:58:21 +00004914
John McCall1d318332010-01-12 00:44:57 +00004915 // If this is a viable builtin, print it.
John McCalla1d7d622010-01-08 00:58:21 +00004916 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004917 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004918 }
4919}
4920
John McCall9aa472c2010-03-19 07:35:19 +00004921static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCallc373d482010-01-27 01:50:18 +00004922 if (isa<UnresolvedLookupExpr>(E))
John McCall9aa472c2010-03-19 07:35:19 +00004923 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00004924
John McCall9aa472c2010-03-19 07:35:19 +00004925 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00004926}
4927
Douglas Gregor904eed32008-11-10 20:40:00 +00004928/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4929/// an overloaded function (C++ [over.over]), where @p From is an
4930/// expression with overloaded function type and @p ToType is the type
4931/// we're trying to resolve to. For example:
4932///
4933/// @code
4934/// int f(double);
4935/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00004936///
Douglas Gregor904eed32008-11-10 20:40:00 +00004937/// int (*pfd)(double) = f; // selects f(double)
4938/// @endcode
4939///
4940/// This routine returns the resulting FunctionDecl if it could be
4941/// resolved, and NULL otherwise. When @p Complain is true, this
4942/// routine will emit diagnostics if there is an error.
4943FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00004944Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004945 bool Complain) {
4946 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00004947 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00004948 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00004949 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004950 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00004951 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00004952 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00004953 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00004954 FunctionType = MemTypePtr->getPointeeType();
4955 IsMember = true;
4956 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004957
4958 // We only look at pointers or references to functions.
Douglas Gregor72e771f2009-07-09 17:16:51 +00004959 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor83314aa2009-07-08 20:55:45 +00004960 if (!FunctionType->isFunctionType())
Douglas Gregor904eed32008-11-10 20:40:00 +00004961 return 0;
4962
4963 // Find the actual overloaded function declaration.
John McCall7bb12da2010-02-02 06:20:04 +00004964 if (From->getType() != Context.OverloadTy)
4965 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004966
Douglas Gregor904eed32008-11-10 20:40:00 +00004967 // C++ [over.over]p1:
4968 // [...] [Note: any redundant set of parentheses surrounding the
4969 // overloaded function name is ignored (5.1). ]
Douglas Gregor904eed32008-11-10 20:40:00 +00004970 // C++ [over.over]p1:
4971 // [...] The overloaded function name can be preceded by the &
4972 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00004973 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
4974 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
4975 if (OvlExpr->hasExplicitTemplateArgs()) {
4976 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
4977 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregor904eed32008-11-10 20:40:00 +00004978 }
4979
Douglas Gregor904eed32008-11-10 20:40:00 +00004980 // Look through all of the overloaded functions, searching for one
4981 // whose type matches exactly.
John McCall9aa472c2010-03-19 07:35:19 +00004982 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004983 bool FoundNonTemplateFunction = false;
John McCall7bb12da2010-02-02 06:20:04 +00004984 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
4985 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00004986 // Look through any using declarations to find the underlying function.
4987 NamedDecl *Fn = (*I)->getUnderlyingDecl();
4988
Douglas Gregor904eed32008-11-10 20:40:00 +00004989 // C++ [over.over]p3:
4990 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00004991 // targets of type "pointer-to-function" or "reference-to-function."
4992 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00004993 // type "pointer-to-member-function."
4994 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00004995
Mike Stump1eb44332009-09-09 15:08:12 +00004996 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00004997 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004998 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00004999 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00005000 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00005001 // static when converting to member pointer.
5002 if (Method->isStatic() == IsMember)
5003 continue;
5004 } else if (IsMember)
5005 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00005006
Douglas Gregor00aeb522009-07-08 23:33:52 +00005007 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005008 // If the name is a function template, template argument deduction is
5009 // done (14.8.2.2), and if the argument deduction succeeds, the
5010 // resulting template argument list is used to generate a single
5011 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00005012 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005013 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00005014 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00005015 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor83314aa2009-07-08 20:55:45 +00005016 if (TemplateDeductionResult Result
John McCall7bb12da2010-02-02 06:20:04 +00005017 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00005018 FunctionType, Specialization, Info)) {
5019 // FIXME: make a note of the failed deduction for diagnostics.
5020 (void)Result;
5021 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005022 // FIXME: If the match isn't exact, shouldn't we just drop this as
5023 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00005024 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00005025 == Context.getCanonicalType(Specialization->getType()));
John McCall9aa472c2010-03-19 07:35:19 +00005026 Matches.push_back(std::make_pair(I.getPair(),
5027 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor83314aa2009-07-08 20:55:45 +00005028 }
John McCallba135432009-11-21 08:51:07 +00005029
5030 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00005031 }
Mike Stump1eb44332009-09-09 15:08:12 +00005032
Chandler Carruthbd647292009-12-29 06:17:27 +00005033 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00005034 // Skip non-static functions when converting to pointer, and static
5035 // when converting to member pointer.
5036 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00005037 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005038
5039 // If we have explicit template arguments, skip non-templates.
John McCall7bb12da2010-02-02 06:20:04 +00005040 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005041 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00005042 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00005043 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00005044
Chandler Carruthbd647292009-12-29 06:17:27 +00005045 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00005046 QualType ResultTy;
5047 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5048 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5049 ResultTy)) {
John McCall9aa472c2010-03-19 07:35:19 +00005050 Matches.push_back(std::make_pair(I.getPair(),
5051 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00005052 FoundNonTemplateFunction = true;
5053 }
Mike Stump1eb44332009-09-09 15:08:12 +00005054 }
Douglas Gregor904eed32008-11-10 20:40:00 +00005055 }
5056
Douglas Gregor00aeb522009-07-08 23:33:52 +00005057 // If there were 0 or 1 matches, we're done.
5058 if (Matches.empty())
5059 return 0;
Sebastian Redl07ab2022009-10-17 21:12:09 +00005060 else if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00005061 FunctionDecl *Result = Matches[0].second;
Sebastian Redl07ab2022009-10-17 21:12:09 +00005062 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCallc373d482010-01-27 01:50:18 +00005063 if (Complain)
John McCall9aa472c2010-03-19 07:35:19 +00005064 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
Sebastian Redl07ab2022009-10-17 21:12:09 +00005065 return Result;
5066 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00005067
5068 // C++ [over.over]p4:
5069 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00005070 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005071 // [...] and any given function template specialization F1 is
5072 // eliminated if the set contains a second function template
5073 // specialization whose function template is more specialized
5074 // than the function template of F1 according to the partial
5075 // ordering rules of 14.5.5.2.
5076
5077 // The algorithm specified above is quadratic. We instead use a
5078 // two-pass algorithm (similar to the one used to identify the
5079 // best viable function in an overload set) that identifies the
5080 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00005081
5082 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5083 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5084 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCallc373d482010-01-27 01:50:18 +00005085
5086 UnresolvedSetIterator Result =
John McCall9aa472c2010-03-19 07:35:19 +00005087 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00005088 TPOC_Other, From->getLocStart(),
5089 PDiag(),
5090 PDiag(diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00005091 << Matches[0].second->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00005092 PDiag(diag::note_ovl_candidate)
5093 << (unsigned) oc_function_template);
John McCall9aa472c2010-03-19 07:35:19 +00005094 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCallc373d482010-01-27 01:50:18 +00005095 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall9aa472c2010-03-19 07:35:19 +00005096 if (Complain) {
5097 DeclAccessPair FoundDecl = Matches[Result - MatchesCopy.begin()].first;
5098 CheckUnresolvedAccess(*this, OvlExpr, FoundDecl);
5099 }
John McCallc373d482010-01-27 01:50:18 +00005100 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00005101 }
Mike Stump1eb44332009-09-09 15:08:12 +00005102
Douglas Gregor312a2022009-09-26 03:56:17 +00005103 // [...] any function template specializations in the set are
5104 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00005105 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCall9aa472c2010-03-19 07:35:19 +00005106 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCallc373d482010-01-27 01:50:18 +00005107 ++I;
5108 else {
John McCall9aa472c2010-03-19 07:35:19 +00005109 Matches[I] = Matches[--N];
5110 Matches.set_size(N);
John McCallc373d482010-01-27 01:50:18 +00005111 }
5112 }
Douglas Gregor312a2022009-09-26 03:56:17 +00005113
Mike Stump1eb44332009-09-09 15:08:12 +00005114 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00005115 // selected function.
John McCallc373d482010-01-27 01:50:18 +00005116 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00005117 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCallc373d482010-01-27 01:50:18 +00005118 if (Complain)
John McCall9aa472c2010-03-19 07:35:19 +00005119 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
5120 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redl07ab2022009-10-17 21:12:09 +00005121 }
Mike Stump1eb44332009-09-09 15:08:12 +00005122
Douglas Gregor00aeb522009-07-08 23:33:52 +00005123 // FIXME: We should probably return the same thing that BestViableFunction
5124 // returns (even if we issue the diagnostics here).
5125 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00005126 << Matches[0].second->getDeclName();
5127 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5128 NoteOverloadCandidate(Matches[I].second);
Douglas Gregor904eed32008-11-10 20:40:00 +00005129 return 0;
5130}
5131
Douglas Gregor4b52e252009-12-21 23:17:24 +00005132/// \brief Given an expression that refers to an overloaded function, try to
5133/// resolve that overloaded function expression down to a single function.
5134///
5135/// This routine can only resolve template-ids that refer to a single function
5136/// template, where that template-id refers to a single template whose template
5137/// arguments are either provided by the template-id or have defaults,
5138/// as described in C++0x [temp.arg.explicit]p3.
5139FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5140 // C++ [over.over]p1:
5141 // [...] [Note: any redundant set of parentheses surrounding the
5142 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00005143 // C++ [over.over]p1:
5144 // [...] The overloaded function name can be preceded by the &
5145 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00005146
5147 if (From->getType() != Context.OverloadTy)
5148 return 0;
5149
5150 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor4b52e252009-12-21 23:17:24 +00005151
5152 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00005153 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00005154 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00005155
5156 TemplateArgumentListInfo ExplicitTemplateArgs;
5157 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor4b52e252009-12-21 23:17:24 +00005158
5159 // Look through all of the overloaded functions, searching for one
5160 // whose type matches exactly.
5161 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00005162 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5163 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00005164 // C++0x [temp.arg.explicit]p3:
5165 // [...] In contexts where deduction is done and fails, or in contexts
5166 // where deduction is not done, if a template argument list is
5167 // specified and it, along with any default template arguments,
5168 // identifies a single function template specialization, then the
5169 // template-id is an lvalue for the function template specialization.
5170 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5171
5172 // C++ [over.over]p2:
5173 // If the name is a function template, template argument deduction is
5174 // done (14.8.2.2), and if the argument deduction succeeds, the
5175 // resulting template argument list is used to generate a single
5176 // function template specialization, which is added to the set of
5177 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00005178 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00005179 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00005180 if (TemplateDeductionResult Result
5181 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5182 Specialization, Info)) {
5183 // FIXME: make a note of the failed deduction for diagnostics.
5184 (void)Result;
5185 continue;
5186 }
5187
5188 // Multiple matches; we can't resolve to a single declaration.
5189 if (Matched)
5190 return 0;
5191
5192 Matched = Specialization;
5193 }
5194
5195 return Matched;
5196}
5197
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005198/// \brief Add a single candidate to the overload set.
5199static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00005200 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00005201 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005202 Expr **Args, unsigned NumArgs,
5203 OverloadCandidateSet &CandidateSet,
5204 bool PartialOverloading) {
John McCall9aa472c2010-03-19 07:35:19 +00005205 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00005206 if (isa<UsingShadowDecl>(Callee))
5207 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5208
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005209 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00005210 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall9aa472c2010-03-19 07:35:19 +00005211 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
John McCall86820f52010-01-26 01:37:31 +00005212 false, false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005213 return;
John McCallba135432009-11-21 08:51:07 +00005214 }
5215
5216 if (FunctionTemplateDecl *FuncTemplate
5217 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00005218 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
5219 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00005220 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00005221 return;
5222 }
5223
5224 assert(false && "unhandled case in overloaded call candidate");
5225
5226 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005227}
5228
5229/// \brief Add the overload candidates named by callee and/or found by argument
5230/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00005231void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005232 Expr **Args, unsigned NumArgs,
5233 OverloadCandidateSet &CandidateSet,
5234 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00005235
5236#ifndef NDEBUG
5237 // Verify that ArgumentDependentLookup is consistent with the rules
5238 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005239 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005240 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5241 // and let Y be the lookup set produced by argument dependent
5242 // lookup (defined as follows). If X contains
5243 //
5244 // -- a declaration of a class member, or
5245 //
5246 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00005247 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005248 //
5249 // -- a declaration that is neither a function or a function
5250 // template
5251 //
5252 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00005253
John McCall3b4294e2009-12-16 12:17:52 +00005254 if (ULE->requiresADL()) {
5255 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5256 E = ULE->decls_end(); I != E; ++I) {
5257 assert(!(*I)->getDeclContext()->isRecord());
5258 assert(isa<UsingShadowDecl>(*I) ||
5259 !(*I)->getDeclContext()->isFunctionOrMethod());
5260 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00005261 }
5262 }
5263#endif
5264
John McCall3b4294e2009-12-16 12:17:52 +00005265 // It would be nice to avoid this copy.
5266 TemplateArgumentListInfo TABuffer;
5267 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5268 if (ULE->hasExplicitTemplateArgs()) {
5269 ULE->copyTemplateArgumentsInto(TABuffer);
5270 ExplicitTemplateArgs = &TABuffer;
5271 }
5272
5273 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5274 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00005275 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00005276 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005277 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00005278
John McCall3b4294e2009-12-16 12:17:52 +00005279 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00005280 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5281 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005282 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005283 CandidateSet,
5284 PartialOverloading);
5285}
John McCall578b69b2009-12-16 08:11:27 +00005286
John McCall3b4294e2009-12-16 12:17:52 +00005287static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5288 Expr **Args, unsigned NumArgs) {
5289 Fn->Destroy(SemaRef.Context);
5290 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5291 Args[Arg]->Destroy(SemaRef.Context);
5292 return SemaRef.ExprError();
5293}
5294
John McCall578b69b2009-12-16 08:11:27 +00005295/// Attempts to recover from a call where no functions were found.
5296///
5297/// Returns true if new candidates were found.
John McCall3b4294e2009-12-16 12:17:52 +00005298static Sema::OwningExprResult
5299BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn,
5300 UnresolvedLookupExpr *ULE,
5301 SourceLocation LParenLoc,
5302 Expr **Args, unsigned NumArgs,
5303 SourceLocation *CommaLocs,
5304 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00005305
5306 CXXScopeSpec SS;
5307 if (ULE->getQualifier()) {
5308 SS.setScopeRep(ULE->getQualifier());
5309 SS.setRange(ULE->getQualifierRange());
5310 }
5311
John McCall3b4294e2009-12-16 12:17:52 +00005312 TemplateArgumentListInfo TABuffer;
5313 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5314 if (ULE->hasExplicitTemplateArgs()) {
5315 ULE->copyTemplateArgumentsInto(TABuffer);
5316 ExplicitTemplateArgs = &TABuffer;
5317 }
5318
John McCall578b69b2009-12-16 08:11:27 +00005319 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5320 Sema::LookupOrdinaryName);
Douglas Gregorbb092ba2009-12-31 05:20:13 +00005321 if (SemaRef.DiagnoseEmptyLookup(/*Scope=*/0, SS, R))
John McCall3b4294e2009-12-16 12:17:52 +00005322 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCall578b69b2009-12-16 08:11:27 +00005323
John McCall3b4294e2009-12-16 12:17:52 +00005324 assert(!R.empty() && "lookup results empty despite recovery");
5325
5326 // Build an implicit member call if appropriate. Just drop the
5327 // casts and such from the call, we don't really care.
5328 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5329 if ((*R.begin())->isCXXClassMember())
5330 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5331 else if (ExplicitTemplateArgs)
5332 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5333 else
5334 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5335
5336 if (NewFn.isInvalid())
5337 return Destroy(SemaRef, Fn, Args, NumArgs);
5338
5339 Fn->Destroy(SemaRef.Context);
5340
5341 // This shouldn't cause an infinite loop because we're giving it
5342 // an expression with non-empty lookup results, which should never
5343 // end up here.
5344 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5345 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5346 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00005347}
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005348
Douglas Gregorf6b89692008-11-26 05:54:23 +00005349/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00005350/// (which eventually refers to the declaration Func) and the call
5351/// arguments Args/NumArgs, attempt to resolve the function call down
5352/// to a specific function. If overload resolution succeeds, returns
5353/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00005354/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00005355/// arguments and Fn, and returns NULL.
John McCall3b4294e2009-12-16 12:17:52 +00005356Sema::OwningExprResult
5357Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE,
5358 SourceLocation LParenLoc,
5359 Expr **Args, unsigned NumArgs,
5360 SourceLocation *CommaLocs,
5361 SourceLocation RParenLoc) {
5362#ifndef NDEBUG
5363 if (ULE->requiresADL()) {
5364 // To do ADL, we must have found an unqualified name.
5365 assert(!ULE->getQualifier() && "qualified name with ADL");
5366
5367 // We don't perform ADL for implicit declarations of builtins.
5368 // Verify that this was correctly set up.
5369 FunctionDecl *F;
5370 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5371 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5372 F->getBuiltinID() && F->isImplicit())
5373 assert(0 && "performing ADL for builtin");
5374
5375 // We don't perform ADL in C.
5376 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5377 }
5378#endif
5379
John McCall5769d612010-02-08 23:07:23 +00005380 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00005381
John McCall3b4294e2009-12-16 12:17:52 +00005382 // Add the functions denoted by the callee to the set of candidate
5383 // functions, including those from argument-dependent lookup.
5384 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00005385
5386 // If we found nothing, try to recover.
5387 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5388 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00005389 if (CandidateSet.empty())
5390 return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs,
5391 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00005392
Douglas Gregorf6b89692008-11-26 05:54:23 +00005393 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005394 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00005395 case OR_Success: {
5396 FunctionDecl *FDecl = Best->Function;
John McCall9aa472c2010-03-19 07:35:19 +00005397 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall3b4294e2009-12-16 12:17:52 +00005398 Fn = FixOverloadedFunctionReference(Fn, FDecl);
5399 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5400 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00005401
5402 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00005403 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00005404 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00005405 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005406 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00005407 break;
5408
5409 case OR_Ambiguous:
5410 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00005411 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005412 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00005413 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005414
5415 case OR_Deleted:
5416 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5417 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00005418 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005419 << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005420 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005421 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00005422 }
5423
5424 // Overload resolution failed. Destroy all of the subexpressions and
5425 // return NULL.
5426 Fn->Destroy(Context);
5427 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5428 Args[Arg]->Destroy(Context);
John McCall3b4294e2009-12-16 12:17:52 +00005429 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00005430}
5431
John McCall6e266892010-01-26 03:27:55 +00005432static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00005433 return Functions.size() > 1 ||
5434 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5435}
5436
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005437/// \brief Create a unary operation that may resolve to an overloaded
5438/// operator.
5439///
5440/// \param OpLoc The location of the operator itself (e.g., '*').
5441///
5442/// \param OpcIn The UnaryOperator::Opcode that describes this
5443/// operator.
5444///
5445/// \param Functions The set of non-member functions that will be
5446/// considered by overload resolution. The caller needs to build this
5447/// set based on the context using, e.g.,
5448/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5449/// set should not contain any member functions; those will be added
5450/// by CreateOverloadedUnaryOp().
5451///
5452/// \param input The input argument.
John McCall6e266892010-01-26 03:27:55 +00005453Sema::OwningExprResult
5454Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
5455 const UnresolvedSetImpl &Fns,
5456 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005457 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5458 Expr *Input = (Expr *)input.get();
5459
5460 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5461 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5462 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5463
5464 Expr *Args[2] = { Input, 0 };
5465 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00005466
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005467 // For post-increment and post-decrement, add the implicit '0' as
5468 // the second argument, so that we know this is a post-increment or
5469 // post-decrement.
5470 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5471 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00005472 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005473 SourceLocation());
5474 NumArgs = 2;
5475 }
5476
5477 if (Input->isTypeDependent()) {
John McCallc373d482010-01-27 01:50:18 +00005478 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00005479 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00005480 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00005481 0, SourceRange(), OpName, OpLoc,
John McCall6e266892010-01-26 03:27:55 +00005482 /*ADL*/ true, IsOverloaded(Fns));
5483 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump1eb44332009-09-09 15:08:12 +00005484
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005485 input.release();
5486 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5487 &Args[0], NumArgs,
5488 Context.DependentTy,
5489 OpLoc));
5490 }
5491
5492 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00005493 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005494
5495 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00005496 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005497
5498 // Add operator candidates that are member functions.
5499 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5500
John McCall6e266892010-01-26 03:27:55 +00005501 // Add candidates from ADL.
5502 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00005503 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00005504 /*ExplicitTemplateArgs*/ 0,
5505 CandidateSet);
5506
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005507 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00005508 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005509
5510 // Perform overload resolution.
5511 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005512 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005513 case OR_Success: {
5514 // We found a built-in operator or an overloaded operator.
5515 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00005516
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005517 if (FnDecl) {
5518 // We matched an overloaded operator. Build a call to that
5519 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00005520
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005521 // Convert the arguments.
5522 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00005523 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00005524
Douglas Gregor5fccd362010-03-03 23:55:11 +00005525 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, Method))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005526 return ExprError();
5527 } else {
5528 // Convert the arguments.
Douglas Gregore1a5c172009-12-23 17:40:29 +00005529 OwningExprResult InputInit
5530 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005531 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00005532 SourceLocation(),
5533 move(input));
5534 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005535 return ExprError();
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005536
Douglas Gregore1a5c172009-12-23 17:40:29 +00005537 input = move(InputInit);
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005538 Input = (Expr *)input.get();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005539 }
5540
5541 // Determine the result type
Anders Carlsson26a2a072009-10-13 21:19:37 +00005542 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00005543
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005544 // Build the actual expression node.
5545 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5546 SourceLocation());
5547 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00005548
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005549 input.release();
Eli Friedman4c3b8962009-11-18 03:58:17 +00005550 Args[0] = Input;
Anders Carlsson26a2a072009-10-13 21:19:37 +00005551 ExprOwningPtr<CallExpr> TheCall(this,
5552 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman4c3b8962009-11-18 03:58:17 +00005553 Args, NumArgs, ResultTy, OpLoc));
Anders Carlsson26a2a072009-10-13 21:19:37 +00005554
5555 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5556 FnDecl))
5557 return ExprError();
5558
5559 return MaybeBindToTemporary(TheCall.release());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005560 } else {
5561 // We matched a built-in operator. Convert the arguments, then
5562 // break out so that we will build the appropriate built-in
5563 // operator node.
5564 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005565 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005566 return ExprError();
5567
5568 break;
5569 }
5570 }
5571
5572 case OR_No_Viable_Function:
5573 // No viable function; fall through to handling this as a
5574 // built-in operator, which will produce an error message for us.
5575 break;
5576
5577 case OR_Ambiguous:
5578 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5579 << UnaryOperator::getOpcodeStr(Opc)
5580 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005581 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005582 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005583 return ExprError();
5584
5585 case OR_Deleted:
5586 Diag(OpLoc, diag::err_ovl_deleted_oper)
5587 << Best->Function->isDeleted()
5588 << UnaryOperator::getOpcodeStr(Opc)
5589 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005590 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005591 return ExprError();
5592 }
5593
5594 // Either we found no viable overloaded operator or we matched a
5595 // built-in operator. In either case, fall through to trying to
5596 // build a built-in operation.
5597 input.release();
5598 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5599}
5600
Douglas Gregor063daf62009-03-13 18:40:31 +00005601/// \brief Create a binary operation that may resolve to an overloaded
5602/// operator.
5603///
5604/// \param OpLoc The location of the operator itself (e.g., '+').
5605///
5606/// \param OpcIn The BinaryOperator::Opcode that describes this
5607/// operator.
5608///
5609/// \param Functions The set of non-member functions that will be
5610/// considered by overload resolution. The caller needs to build this
5611/// set based on the context using, e.g.,
5612/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5613/// set should not contain any member functions; those will be added
5614/// by CreateOverloadedBinOp().
5615///
5616/// \param LHS Left-hand argument.
5617/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00005618Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00005619Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005620 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00005621 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00005622 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00005623 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005624 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00005625
5626 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5627 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5628 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5629
5630 // If either side is type-dependent, create an appropriate dependent
5631 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005632 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00005633 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005634 // If there are no functions to store, just build a dependent
5635 // BinaryOperator or CompoundAssignment.
5636 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5637 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5638 Context.DependentTy, OpLoc));
5639
5640 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5641 Context.DependentTy,
5642 Context.DependentTy,
5643 Context.DependentTy,
5644 OpLoc));
5645 }
John McCall6e266892010-01-26 03:27:55 +00005646
5647 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00005648 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00005649 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00005650 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00005651 0, SourceRange(), OpName, OpLoc,
John McCall6e266892010-01-26 03:27:55 +00005652 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump1eb44332009-09-09 15:08:12 +00005653
John McCall6e266892010-01-26 03:27:55 +00005654 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00005655 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00005656 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00005657 Context.DependentTy,
5658 OpLoc));
5659 }
5660
5661 // If this is the .* operator, which is not overloadable, just
5662 // create a built-in binary operator.
5663 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005664 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005665
Sebastian Redl275c2b42009-11-18 23:10:33 +00005666 // If this is the assignment operator, we only perform overload resolution
5667 // if the left-hand side is a class or enumeration type. This is actually
5668 // a hack. The standard requires that we do overload resolution between the
5669 // various built-in candidates, but as DR507 points out, this can lead to
5670 // problems. So we do it this way, which pretty much follows what GCC does.
5671 // Note that we go the traditional code path for compound assignment forms.
5672 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005673 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005674
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005675 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00005676 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00005677
5678 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00005679 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00005680
5681 // Add operator candidates that are member functions.
5682 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5683
John McCall6e266892010-01-26 03:27:55 +00005684 // Add candidates from ADL.
5685 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
5686 Args, 2,
5687 /*ExplicitTemplateArgs*/ 0,
5688 CandidateSet);
5689
Douglas Gregor063daf62009-03-13 18:40:31 +00005690 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00005691 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00005692
5693 // Perform overload resolution.
5694 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005695 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005696 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00005697 // We found a built-in operator or an overloaded operator.
5698 FunctionDecl *FnDecl = Best->Function;
5699
5700 if (FnDecl) {
5701 // We matched an overloaded operator. Build a call to that
5702 // operator.
5703
5704 // Convert the arguments.
5705 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00005706 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00005707 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00005708
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005709 OwningExprResult Arg1
5710 = PerformCopyInitialization(
5711 InitializedEntity::InitializeParameter(
5712 FnDecl->getParamDecl(0)),
5713 SourceLocation(),
5714 Owned(Args[1]));
5715 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00005716 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005717
Douglas Gregor5fccd362010-03-03 23:55:11 +00005718 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
5719 Method))
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005720 return ExprError();
5721
5722 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00005723 } else {
5724 // Convert the arguments.
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005725 OwningExprResult Arg0
5726 = PerformCopyInitialization(
5727 InitializedEntity::InitializeParameter(
5728 FnDecl->getParamDecl(0)),
5729 SourceLocation(),
5730 Owned(Args[0]));
5731 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00005732 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005733
5734 OwningExprResult Arg1
5735 = PerformCopyInitialization(
5736 InitializedEntity::InitializeParameter(
5737 FnDecl->getParamDecl(1)),
5738 SourceLocation(),
5739 Owned(Args[1]));
5740 if (Arg1.isInvalid())
5741 return ExprError();
5742 Args[0] = LHS = Arg0.takeAs<Expr>();
5743 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00005744 }
5745
5746 // Determine the result type
5747 QualType ResultTy
John McCall183700f2009-09-21 23:43:11 +00005748 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor063daf62009-03-13 18:40:31 +00005749 ResultTy = ResultTy.getNonReferenceType();
5750
5751 // Build the actual expression node.
5752 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00005753 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00005754 UsualUnaryConversions(FnExpr);
5755
Anders Carlsson15ea3782009-10-13 22:43:21 +00005756 ExprOwningPtr<CXXOperatorCallExpr>
5757 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5758 Args, 2, ResultTy,
5759 OpLoc));
5760
5761 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5762 FnDecl))
5763 return ExprError();
5764
5765 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor063daf62009-03-13 18:40:31 +00005766 } else {
5767 // We matched a built-in operator. Convert the arguments, then
5768 // break out so that we will build the appropriate built-in
5769 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005770 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005771 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005772 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00005773 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00005774 return ExprError();
5775
5776 break;
5777 }
5778 }
5779
Douglas Gregor33074752009-09-30 21:46:01 +00005780 case OR_No_Viable_Function: {
5781 // C++ [over.match.oper]p9:
5782 // If the operator is the operator , [...] and there are no
5783 // viable functions, then the operator is assumed to be the
5784 // built-in operator and interpreted according to clause 5.
5785 if (Opc == BinaryOperator::Comma)
5786 break;
5787
Sebastian Redl8593c782009-05-21 11:50:50 +00005788 // For class as left operand for assignment or compound assigment operator
5789 // do not fall through to handling in built-in, but report that no overloaded
5790 // assignment operator found
Douglas Gregor33074752009-09-30 21:46:01 +00005791 OwningExprResult Result = ExprError();
5792 if (Args[0]->getType()->isRecordType() &&
5793 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00005794 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5795 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005796 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00005797 } else {
5798 // No viable function; try to create a built-in operation, which will
5799 // produce an error. Then, show the non-viable candidates.
5800 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00005801 }
Douglas Gregor33074752009-09-30 21:46:01 +00005802 assert(Result.isInvalid() &&
5803 "C++ binary operator overloading is missing candidates!");
5804 if (Result.isInvalid())
John McCallcbce6062010-01-12 07:18:19 +00005805 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005806 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00005807 return move(Result);
5808 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005809
5810 case OR_Ambiguous:
5811 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5812 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005813 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005814 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005815 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00005816 return ExprError();
5817
5818 case OR_Deleted:
5819 Diag(OpLoc, diag::err_ovl_deleted_oper)
5820 << Best->Function->isDeleted()
5821 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005822 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005823 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00005824 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00005825 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005826
Douglas Gregor33074752009-09-30 21:46:01 +00005827 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005828 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005829}
5830
Sebastian Redlf322ed62009-10-29 20:17:01 +00005831Action::OwningExprResult
5832Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5833 SourceLocation RLoc,
5834 ExprArg Base, ExprArg Idx) {
5835 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5836 static_cast<Expr*>(Idx.get()) };
5837 DeclarationName OpName =
5838 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5839
5840 // If either side is type-dependent, create an appropriate dependent
5841 // expression.
5842 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5843
John McCallc373d482010-01-27 01:50:18 +00005844 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00005845 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00005846 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00005847 0, SourceRange(), OpName, LLoc,
John McCall7453ed42009-11-22 00:44:51 +00005848 /*ADL*/ true, /*Overloaded*/ false);
John McCallf7a1a742009-11-24 19:00:30 +00005849 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00005850
5851 Base.release();
5852 Idx.release();
5853 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5854 Args, 2,
5855 Context.DependentTy,
5856 RLoc));
5857 }
5858
5859 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00005860 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00005861
5862 // Subscript can only be overloaded as a member function.
5863
5864 // Add operator candidates that are member functions.
5865 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5866
5867 // Add builtin operator candidates.
5868 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5869
5870 // Perform overload resolution.
5871 OverloadCandidateSet::iterator Best;
5872 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5873 case OR_Success: {
5874 // We found a built-in operator or an overloaded operator.
5875 FunctionDecl *FnDecl = Best->Function;
5876
5877 if (FnDecl) {
5878 // We matched an overloaded operator. Build a call to that
5879 // operator.
5880
John McCall9aa472c2010-03-19 07:35:19 +00005881 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallc373d482010-01-27 01:50:18 +00005882
Sebastian Redlf322ed62009-10-29 20:17:01 +00005883 // Convert the arguments.
5884 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregor5fccd362010-03-03 23:55:11 +00005885 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
5886 Method))
Sebastian Redlf322ed62009-10-29 20:17:01 +00005887 return ExprError();
5888
Anders Carlsson38f88ab2010-01-29 18:37:50 +00005889 // Convert the arguments.
5890 OwningExprResult InputInit
5891 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
5892 FnDecl->getParamDecl(0)),
5893 SourceLocation(),
5894 Owned(Args[1]));
5895 if (InputInit.isInvalid())
5896 return ExprError();
5897
5898 Args[1] = InputInit.takeAs<Expr>();
5899
Sebastian Redlf322ed62009-10-29 20:17:01 +00005900 // Determine the result type
5901 QualType ResultTy
5902 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5903 ResultTy = ResultTy.getNonReferenceType();
5904
5905 // Build the actual expression node.
5906 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5907 LLoc);
5908 UsualUnaryConversions(FnExpr);
5909
5910 Base.release();
5911 Idx.release();
5912 ExprOwningPtr<CXXOperatorCallExpr>
5913 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5914 FnExpr, Args, 2,
5915 ResultTy, RLoc));
5916
5917 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5918 FnDecl))
5919 return ExprError();
5920
5921 return MaybeBindToTemporary(TheCall.release());
5922 } else {
5923 // We matched a built-in operator. Convert the arguments, then
5924 // break out so that we will build the appropriate built-in
5925 // operator node.
5926 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005927 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00005928 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00005929 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00005930 return ExprError();
5931
5932 break;
5933 }
5934 }
5935
5936 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00005937 if (CandidateSet.empty())
5938 Diag(LLoc, diag::err_ovl_no_oper)
5939 << Args[0]->getType() << /*subscript*/ 0
5940 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5941 else
5942 Diag(LLoc, diag::err_ovl_no_viable_subscript)
5943 << Args[0]->getType()
5944 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005945 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall1eb3e102010-01-07 02:04:15 +00005946 "[]", LLoc);
5947 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00005948 }
5949
5950 case OR_Ambiguous:
5951 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5952 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005953 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redlf322ed62009-10-29 20:17:01 +00005954 "[]", LLoc);
5955 return ExprError();
5956
5957 case OR_Deleted:
5958 Diag(LLoc, diag::err_ovl_deleted_oper)
5959 << Best->Function->isDeleted() << "[]"
5960 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005961 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall81201622010-01-08 04:41:39 +00005962 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00005963 return ExprError();
5964 }
5965
5966 // We matched a built-in operator; build it.
5967 Base.release();
5968 Idx.release();
5969 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5970 Owned(Args[1]), RLoc);
5971}
5972
Douglas Gregor88a35142008-12-22 05:46:06 +00005973/// BuildCallToMemberFunction - Build a call to a member
5974/// function. MemExpr is the expression that refers to the member
5975/// function (and includes the object parameter), Args/NumArgs are the
5976/// arguments to the function call (not including the object
5977/// parameter). The caller needs to validate that the member
5978/// expression refers to a member function or an overloaded member
5979/// function.
John McCallaa81e162009-12-01 22:10:20 +00005980Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00005981Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5982 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00005983 unsigned NumArgs, SourceLocation *CommaLocs,
5984 SourceLocation RParenLoc) {
5985 // Dig out the member expression. This holds both the object
5986 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00005987 Expr *NakedMemExpr = MemExprE->IgnoreParens();
5988
John McCall129e2df2009-11-30 22:42:35 +00005989 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00005990 CXXMethodDecl *Method = 0;
Douglas Gregor5fccd362010-03-03 23:55:11 +00005991 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00005992 if (isa<MemberExpr>(NakedMemExpr)) {
5993 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00005994 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
Douglas Gregor5fccd362010-03-03 23:55:11 +00005995 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00005996 } else {
5997 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00005998 Qualifier = UnresExpr->getQualifier();
5999
John McCall701c89e2009-12-03 04:06:58 +00006000 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00006001
Douglas Gregor88a35142008-12-22 05:46:06 +00006002 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00006003 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00006004
John McCallaa81e162009-12-01 22:10:20 +00006005 // FIXME: avoid copy.
6006 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6007 if (UnresExpr->hasExplicitTemplateArgs()) {
6008 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6009 TemplateArgs = &TemplateArgsBuffer;
6010 }
6011
John McCall129e2df2009-11-30 22:42:35 +00006012 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6013 E = UnresExpr->decls_end(); I != E; ++I) {
6014
John McCall701c89e2009-12-03 04:06:58 +00006015 NamedDecl *Func = *I;
6016 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6017 if (isa<UsingShadowDecl>(Func))
6018 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6019
John McCall129e2df2009-11-30 22:42:35 +00006020 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006021 // If explicit template arguments were provided, we can't call a
6022 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00006023 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006024 continue;
6025
John McCall9aa472c2010-03-19 07:35:19 +00006026 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCall86820f52010-01-26 01:37:31 +00006027 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00006028 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00006029 } else {
John McCall129e2df2009-11-30 22:42:35 +00006030 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00006031 I.getPair(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00006032 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00006033 CandidateSet,
6034 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00006035 }
Douglas Gregordec06662009-08-21 18:42:58 +00006036 }
Mike Stump1eb44332009-09-09 15:08:12 +00006037
John McCall129e2df2009-11-30 22:42:35 +00006038 DeclarationName DeclName = UnresExpr->getMemberName();
6039
Douglas Gregor88a35142008-12-22 05:46:06 +00006040 OverloadCandidateSet::iterator Best;
John McCall129e2df2009-11-30 22:42:35 +00006041 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00006042 case OR_Success:
6043 Method = cast<CXXMethodDecl>(Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +00006044 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Douglas Gregor88a35142008-12-22 05:46:06 +00006045 break;
6046
6047 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00006048 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00006049 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00006050 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006051 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00006052 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006053 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006054
6055 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00006056 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00006057 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006058 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00006059 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006060 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006061
6062 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00006063 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006064 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00006065 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006066 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006067 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006068 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006069 }
6070
Douglas Gregor699ee522009-11-20 19:42:02 +00006071 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCallaa81e162009-12-01 22:10:20 +00006072
John McCallaa81e162009-12-01 22:10:20 +00006073 // If overload resolution picked a static member, build a
6074 // non-member call based on that function.
6075 if (Method->isStatic()) {
6076 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6077 Args, NumArgs, RParenLoc);
6078 }
6079
John McCall129e2df2009-11-30 22:42:35 +00006080 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00006081 }
6082
6083 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00006084 ExprOwningPtr<CXXMemberCallExpr>
John McCallaa81e162009-12-01 22:10:20 +00006085 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00006086 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00006087 Method->getResultType().getNonReferenceType(),
6088 RParenLoc));
6089
Anders Carlssoneed3e692009-10-10 00:06:20 +00006090 // Check for a valid return type.
6091 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6092 TheCall.get(), Method))
John McCallaa81e162009-12-01 22:10:20 +00006093 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00006094
Douglas Gregor88a35142008-12-22 05:46:06 +00006095 // Convert the object argument (for a non-static member function call).
John McCallaa81e162009-12-01 22:10:20 +00006096 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00006097 if (!Method->isStatic() &&
Douglas Gregor5fccd362010-03-03 23:55:11 +00006098 PerformObjectArgumentInitialization(ObjectArg, Qualifier, Method))
John McCallaa81e162009-12-01 22:10:20 +00006099 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006100 MemExpr->setBase(ObjectArg);
6101
6102 // Convert the rest of the arguments
Douglas Gregor72564e72009-02-26 23:50:07 +00006103 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00006104 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00006105 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00006106 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006107
Anders Carlssond406bf02009-08-16 01:56:34 +00006108 if (CheckFunctionCall(Method, TheCall.get()))
John McCallaa81e162009-12-01 22:10:20 +00006109 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00006110
John McCallaa81e162009-12-01 22:10:20 +00006111 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor88a35142008-12-22 05:46:06 +00006112}
6113
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006114/// BuildCallToObjectOfClassType - Build a call to an object of class
6115/// type (C++ [over.call.object]), which can end up invoking an
6116/// overloaded function call operator (@c operator()) or performing a
6117/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00006118Sema::ExprResult
6119Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00006120 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006121 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00006122 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006123 SourceLocation RParenLoc) {
6124 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00006125 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006126
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006127 // C++ [over.call.object]p1:
6128 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00006129 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006130 // candidate functions includes at least the function call
6131 // operators of T. The function call operators of T are obtained by
6132 // ordinary lookup of the name operator() in the context of
6133 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00006134 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00006135 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00006136
6137 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006138 PDiag(diag::err_incomplete_object_call)
Douglas Gregor593564b2009-11-15 07:48:03 +00006139 << Object->getSourceRange()))
6140 return true;
6141
John McCalla24dc2e2009-11-17 02:14:36 +00006142 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6143 LookupQualifiedName(R, Record->getDecl());
6144 R.suppressDiagnostics();
6145
Douglas Gregor593564b2009-11-15 07:48:03 +00006146 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00006147 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00006148 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCall86820f52010-01-26 01:37:31 +00006149 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006150 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00006151 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00006152
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006153 // C++ [over.call.object]p2:
6154 // In addition, for each conversion function declared in T of the
6155 // form
6156 //
6157 // operator conversion-type-id () cv-qualifier;
6158 //
6159 // where cv-qualifier is the same cv-qualification as, or a
6160 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00006161 // denotes the type "pointer to function of (P1,...,Pn) returning
6162 // R", or the type "reference to pointer to function of
6163 // (P1,...,Pn) returning R", or the type "reference to function
6164 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006165 // is also considered as a candidate function. Similarly,
6166 // surrogate call functions are added to the set of candidate
6167 // functions for each conversion function declared in an
6168 // accessible base class provided the function is not hidden
6169 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00006170 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00006171 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00006172 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00006173 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00006174 NamedDecl *D = *I;
6175 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6176 if (isa<UsingShadowDecl>(D))
6177 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6178
Douglas Gregor4a27d702009-10-21 06:18:39 +00006179 // Skip over templated conversion functions; they aren't
6180 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00006181 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00006182 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006183
John McCall701c89e2009-12-03 04:06:58 +00006184 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00006185
Douglas Gregor4a27d702009-10-21 06:18:39 +00006186 // Strip the reference type (if any) and then the pointer type (if
6187 // any) to get down to what might be a function type.
6188 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6189 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6190 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006191
Douglas Gregor4a27d702009-10-21 06:18:39 +00006192 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall9aa472c2010-03-19 07:35:19 +00006193 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00006194 Object->getType(), Args, NumArgs,
6195 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006196 }
Mike Stump1eb44332009-09-09 15:08:12 +00006197
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006198 // Perform overload resolution.
6199 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006200 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006201 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006202 // Overload resolution succeeded; we'll build the appropriate call
6203 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006204 break;
6205
6206 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00006207 if (CandidateSet.empty())
6208 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6209 << Object->getType() << /*call*/ 1
6210 << Object->getSourceRange();
6211 else
6212 Diag(Object->getSourceRange().getBegin(),
6213 diag::err_ovl_no_viable_object_call)
6214 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006215 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006216 break;
6217
6218 case OR_Ambiguous:
6219 Diag(Object->getSourceRange().getBegin(),
6220 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00006221 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006222 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006223 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006224
6225 case OR_Deleted:
6226 Diag(Object->getSourceRange().getBegin(),
6227 diag::err_ovl_deleted_object_call)
6228 << Best->Function->isDeleted()
6229 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006230 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006231 break;
Mike Stump1eb44332009-09-09 15:08:12 +00006232 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006233
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006234 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006235 // We had an error; delete all of the subexpressions and return
6236 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00006237 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006238 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00006239 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006240 return true;
6241 }
6242
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006243 if (Best->Function == 0) {
6244 // Since there is no function declaration, this is one of the
6245 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00006246 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006247 = cast<CXXConversionDecl>(
6248 Best->Conversions[0].UserDefined.ConversionFunction);
6249
John McCall9aa472c2010-03-19 07:35:19 +00006250 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall41d89032010-01-28 01:54:34 +00006251
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006252 // We selected one of the surrogate functions that converts the
6253 // object parameter to a function pointer. Perform the conversion
6254 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00006255
6256 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00006257 // and then call it.
Eli Friedmanc8c771e2009-12-09 04:52:43 +00006258 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00006259
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00006260 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00006261 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
6262 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006263 }
6264
John McCall9aa472c2010-03-19 07:35:19 +00006265 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall41d89032010-01-28 01:54:34 +00006266
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006267 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6268 // that calls this method, using Object for the implicit object
6269 // parameter and passing along the remaining arguments.
6270 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00006271 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006272
6273 unsigned NumArgsInProto = Proto->getNumArgs();
6274 unsigned NumArgsToCheck = NumArgs;
6275
6276 // Build the full argument list for the method call (the
6277 // implicit object parameter is placed at the beginning of the
6278 // list).
6279 Expr **MethodArgs;
6280 if (NumArgs < NumArgsInProto) {
6281 NumArgsToCheck = NumArgsInProto;
6282 MethodArgs = new Expr*[NumArgsInProto + 1];
6283 } else {
6284 MethodArgs = new Expr*[NumArgs + 1];
6285 }
6286 MethodArgs[0] = Object;
6287 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6288 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00006289
6290 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00006291 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006292 UsualUnaryConversions(NewFn);
6293
6294 // Once we've built TheCall, all of the expressions are properly
6295 // owned.
6296 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00006297 ExprOwningPtr<CXXOperatorCallExpr>
6298 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00006299 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00006300 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006301 delete [] MethodArgs;
6302
Anders Carlsson07d68f12009-10-13 21:49:31 +00006303 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6304 Method))
6305 return true;
6306
Douglas Gregor518fda12009-01-13 05:10:00 +00006307 // We may have default arguments. If so, we need to allocate more
6308 // slots in the call for them.
6309 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00006310 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00006311 else if (NumArgs > NumArgsInProto)
6312 NumArgsToCheck = NumArgsInProto;
6313
Chris Lattner312531a2009-04-12 08:11:20 +00006314 bool IsError = false;
6315
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006316 // Initialize the implicit object parameter.
Douglas Gregor5fccd362010-03-03 23:55:11 +00006317 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
6318 Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006319 TheCall->setArg(0, Object);
6320
Chris Lattner312531a2009-04-12 08:11:20 +00006321
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006322 // Check the argument types.
6323 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006324 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00006325 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006326 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00006327
Douglas Gregor518fda12009-01-13 05:10:00 +00006328 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00006329
6330 OwningExprResult InputInit
6331 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6332 Method->getParamDecl(i)),
6333 SourceLocation(), Owned(Arg));
6334
6335 IsError |= InputInit.isInvalid();
6336 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00006337 } else {
Douglas Gregord47c47d2009-11-09 19:27:57 +00006338 OwningExprResult DefArg
6339 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6340 if (DefArg.isInvalid()) {
6341 IsError = true;
6342 break;
6343 }
6344
6345 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00006346 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006347
6348 TheCall->setArg(i + 1, Arg);
6349 }
6350
6351 // If this is a variadic call, handle args passed through "...".
6352 if (Proto->isVariadic()) {
6353 // Promote the arguments (C99 6.5.2.2p7).
6354 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6355 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00006356 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006357 TheCall->setArg(i + 1, Arg);
6358 }
6359 }
6360
Chris Lattner312531a2009-04-12 08:11:20 +00006361 if (IsError) return true;
6362
Anders Carlssond406bf02009-08-16 01:56:34 +00006363 if (CheckFunctionCall(Method, TheCall.get()))
6364 return true;
6365
Anders Carlssona303f9e2009-08-16 03:53:54 +00006366 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006367}
6368
Douglas Gregor8ba10742008-11-20 16:27:02 +00006369/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00006370/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00006371/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006372Sema::OwningExprResult
6373Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6374 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00006375 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00006376
John McCall5769d612010-02-08 23:07:23 +00006377 SourceLocation Loc = Base->getExprLoc();
6378
Douglas Gregor8ba10742008-11-20 16:27:02 +00006379 // C++ [over.ref]p1:
6380 //
6381 // [...] An expression x->m is interpreted as (x.operator->())->m
6382 // for a class object x of type T if T::operator->() exists and if
6383 // the operator is selected as the best match function by the
6384 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00006385 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00006386 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00006387 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006388
John McCall5769d612010-02-08 23:07:23 +00006389 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00006390 PDiag(diag::err_typecheck_incomplete_tag)
6391 << Base->getSourceRange()))
6392 return ExprError();
6393
John McCalla24dc2e2009-11-17 02:14:36 +00006394 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6395 LookupQualifiedName(R, BaseRecord->getDecl());
6396 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00006397
6398 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00006399 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00006400 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00006401 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00006402 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00006403
6404 // Perform overload resolution.
6405 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006406 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00006407 case OR_Success:
6408 // Overload resolution succeeded; we'll build the call below.
6409 break;
6410
6411 case OR_No_Viable_Function:
6412 if (CandidateSet.empty())
6413 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006414 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006415 else
6416 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006417 << "operator->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006418 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006419 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006420
6421 case OR_Ambiguous:
6422 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00006423 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006424 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006425 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006426
6427 case OR_Deleted:
6428 Diag(OpLoc, diag::err_ovl_deleted_oper)
6429 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00006430 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006431 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006432 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006433 }
6434
John McCall9aa472c2010-03-19 07:35:19 +00006435 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
6436
Douglas Gregor8ba10742008-11-20 16:27:02 +00006437 // Convert the object parameter.
6438 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor5fccd362010-03-03 23:55:11 +00006439 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006440 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00006441
6442 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006443 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006444
6445 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00006446 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6447 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00006448 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00006449
6450 QualType ResultTy = Method->getResultType().getNonReferenceType();
6451 ExprOwningPtr<CXXOperatorCallExpr>
6452 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6453 &Base, 1, ResultTy, OpLoc));
6454
6455 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6456 Method))
6457 return ExprError();
6458 return move(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00006459}
6460
Douglas Gregor904eed32008-11-10 20:40:00 +00006461/// FixOverloadedFunctionReference - E is an expression that refers to
6462/// a C++ overloaded function (possibly with some parentheses and
6463/// perhaps a '&' around it). We have resolved the overloaded function
6464/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00006465/// refer (possibly indirectly) to Fn. Returns the new expr.
6466Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006467 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor699ee522009-11-20 19:42:02 +00006468 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
6469 if (SubExpr == PE->getSubExpr())
6470 return PE->Retain();
6471
6472 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6473 }
6474
6475 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6476 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00006477 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00006478 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00006479 "Implicit cast type cannot be determined from overload");
Douglas Gregor699ee522009-11-20 19:42:02 +00006480 if (SubExpr == ICE->getSubExpr())
6481 return ICE->Retain();
6482
6483 return new (Context) ImplicitCastExpr(ICE->getType(),
6484 ICE->getCastKind(),
6485 SubExpr,
6486 ICE->isLvalueCast());
6487 }
6488
6489 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006490 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00006491 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00006492 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6493 if (Method->isStatic()) {
6494 // Do nothing: static member functions aren't any different
6495 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00006496 } else {
John McCallf7a1a742009-11-24 19:00:30 +00006497 // Fix the sub expression, which really has to be an
6498 // UnresolvedLookupExpr holding an overloaded member function
6499 // or template.
John McCallba135432009-11-21 08:51:07 +00006500 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6501 if (SubExpr == UnOp->getSubExpr())
6502 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00006503
John McCallba135432009-11-21 08:51:07 +00006504 assert(isa<DeclRefExpr>(SubExpr)
6505 && "fixed to something other than a decl ref");
6506 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6507 && "fixed to a member ref with no nested name qualifier");
6508
6509 // We have taken the address of a pointer to member
6510 // function. Perform the computation here so that we get the
6511 // appropriate pointer to member type.
6512 QualType ClassType
6513 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6514 QualType MemPtrType
6515 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6516
6517 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6518 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00006519 }
6520 }
Douglas Gregor699ee522009-11-20 19:42:02 +00006521 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6522 if (SubExpr == UnOp->getSubExpr())
6523 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00006524
Douglas Gregor699ee522009-11-20 19:42:02 +00006525 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6526 Context.getPointerType(SubExpr->getType()),
6527 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00006528 }
John McCallba135432009-11-21 08:51:07 +00006529
6530 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00006531 // FIXME: avoid copy.
6532 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00006533 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00006534 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6535 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00006536 }
6537
John McCallba135432009-11-21 08:51:07 +00006538 return DeclRefExpr::Create(Context,
6539 ULE->getQualifier(),
6540 ULE->getQualifierRange(),
6541 Fn,
6542 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00006543 Fn->getType(),
6544 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00006545 }
6546
John McCall129e2df2009-11-30 22:42:35 +00006547 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00006548 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00006549 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6550 if (MemExpr->hasExplicitTemplateArgs()) {
6551 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6552 TemplateArgs = &TemplateArgsBuffer;
6553 }
John McCalld5532b62009-11-23 01:53:49 +00006554
John McCallaa81e162009-12-01 22:10:20 +00006555 Expr *Base;
6556
6557 // If we're filling in
6558 if (MemExpr->isImplicitAccess()) {
6559 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6560 return DeclRefExpr::Create(Context,
6561 MemExpr->getQualifier(),
6562 MemExpr->getQualifierRange(),
6563 Fn,
6564 MemExpr->getMemberLoc(),
6565 Fn->getType(),
6566 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00006567 } else {
6568 SourceLocation Loc = MemExpr->getMemberLoc();
6569 if (MemExpr->getQualifier())
6570 Loc = MemExpr->getQualifierRange().getBegin();
6571 Base = new (Context) CXXThisExpr(Loc,
6572 MemExpr->getBaseType(),
6573 /*isImplicit=*/true);
6574 }
John McCallaa81e162009-12-01 22:10:20 +00006575 } else
6576 Base = MemExpr->getBase()->Retain();
6577
6578 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00006579 MemExpr->isArrow(),
6580 MemExpr->getQualifier(),
6581 MemExpr->getQualifierRange(),
6582 Fn,
John McCalld5532b62009-11-23 01:53:49 +00006583 MemExpr->getMemberLoc(),
John McCallaa81e162009-12-01 22:10:20 +00006584 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00006585 Fn->getType());
6586 }
6587
Douglas Gregor699ee522009-11-20 19:42:02 +00006588 assert(false && "Invalid reference to overloaded function");
6589 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00006590}
6591
Douglas Gregor20093b42009-12-09 23:02:17 +00006592Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
6593 FunctionDecl *Fn) {
6594 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
6595}
6596
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006597} // end namespace clang