blob: e039669257ba34bbfa97b30403bd1800d2f91525 [file] [log] [blame]
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor4c2458a2009-12-22 21:44:34 +000016#include "SemaInit.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000027#include <algorithm>
28
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000055 ICC_Conversion
56 };
57 return Category[(int)Kind];
58}
59
60/// GetConversionRank - Retrieve the implicit conversion rank
61/// corresponding to the given implicit conversion kind.
62ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
63 static const ImplicitConversionRank
64 Rank[(int)ICK_Num_Conversion_Kinds] = {
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +000070 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000071 ICR_Promotion,
72 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000073 ICR_Promotion,
74 ICR_Conversion,
75 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000076 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000081 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000082 ICR_Conversion,
Chandler Carruth23a370f2010-02-25 07:20:54 +000083 ICR_Complex_Real_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000084 };
85 return Rank[(int)Kind];
86}
87
88/// GetImplicitConversionName - Return the name of this kind of
89/// implicit conversion.
90const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +000091 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000092 "No conversion",
93 "Lvalue-to-rvalue",
94 "Array-to-pointer",
95 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +000096 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000097 "Qualification",
98 "Integral promotion",
99 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000100 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000101 "Integral conversion",
102 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000103 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000104 "Floating-integral conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000105 "Complex-real conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000106 "Pointer conversion",
107 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000108 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000109 "Compatible-types conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000110 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000111 };
112 return Name[Kind];
113}
114
Douglas Gregor60d62c22008-10-31 16:23:19 +0000115/// StandardConversionSequence - Set the standard conversion
116/// sequence to the identity conversion.
117void StandardConversionSequence::setAsIdentityConversion() {
118 First = ICK_Identity;
119 Second = ICK_Identity;
120 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000121 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000122 ReferenceBinding = false;
123 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000124 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000125 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000126}
127
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000128/// getRank - Retrieve the rank of this standard conversion sequence
129/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
130/// implicit conversions.
131ImplicitConversionRank StandardConversionSequence::getRank() const {
132 ImplicitConversionRank Rank = ICR_Exact_Match;
133 if (GetConversionRank(First) > Rank)
134 Rank = GetConversionRank(First);
135 if (GetConversionRank(Second) > Rank)
136 Rank = GetConversionRank(Second);
137 if (GetConversionRank(Third) > Rank)
138 Rank = GetConversionRank(Third);
139 return Rank;
140}
141
142/// isPointerConversionToBool - Determines whether this conversion is
143/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000144/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000145/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000146bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000147 // Note that FromType has not necessarily been transformed by the
148 // array-to-pointer or function-to-pointer implicit conversions, so
149 // check for their presence as well as checking whether FromType is
150 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000151 if (getToType(1)->isBooleanType() &&
John McCall1d318332010-01-12 00:44:57 +0000152 (getFromType()->isPointerType() || getFromType()->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000153 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154 return true;
155
156 return false;
157}
158
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000159/// isPointerConversionToVoidPointer - Determines whether this
160/// conversion is a conversion of a pointer to a void pointer. This is
161/// used as part of the ranking of standard conversion sequences (C++
162/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000163bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000166 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000167 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000168
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
174
Douglas Gregor01919692009-12-13 21:37:05 +0000175 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000185 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000186 bool PrintedSomething = false;
187 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000188 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000189 PrintedSomething = true;
190 }
191
192 if (Second != ICK_Identity) {
193 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000194 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000195 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000196 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000197
198 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000199 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000200 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000201 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000202 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000203 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000204 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000205 PrintedSomething = true;
206 }
207
208 if (Third != ICK_Identity) {
209 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000210 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000211 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000212 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000213 PrintedSomething = true;
214 }
215
216 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000217 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000218 }
219}
220
221/// DebugPrint - Print this user-defined conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000224 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000225 if (Before.First || Before.Second || Before.Third) {
226 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000227 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000228 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000229 OS << "'" << ConversionFunction->getNameAsString() << "'";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000230 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000231 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000232 After.DebugPrint();
233 }
234}
235
236/// DebugPrint - Print this implicit conversion sequence to standard
237/// error. Useful for debugging overloading issues.
238void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000239 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000240 switch (ConversionKind) {
241 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000242 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000243 Standard.DebugPrint();
244 break;
245 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000246 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000247 UserDefined.DebugPrint();
248 break;
249 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000250 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000251 break;
John McCall1d318332010-01-12 00:44:57 +0000252 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000253 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000254 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000255 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000256 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000257 break;
258 }
259
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000260 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000261}
262
John McCall1d318332010-01-12 00:44:57 +0000263void AmbiguousConversionSequence::construct() {
264 new (&conversions()) ConversionSet();
265}
266
267void AmbiguousConversionSequence::destruct() {
268 conversions().~ConversionSet();
269}
270
271void
272AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
273 FromTypePtr = O.FromTypePtr;
274 ToTypePtr = O.ToTypePtr;
275 new (&conversions()) ConversionSet(O.conversions());
276}
277
278
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000279// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000280// overload of the declarations in Old. This routine returns false if
281// New and Old cannot be overloaded, e.g., if New has the same
282// signature as some function in Old (C++ 1.3.10) or if the Old
283// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000284// it does return false, MatchedDecl will point to the decl that New
285// cannot be overloaded with. This decl may be a UsingShadowDecl on
286// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000287//
288// Example: Given the following input:
289//
290// void f(int, float); // #1
291// void f(int, int); // #2
292// int f(int, int); // #3
293//
294// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000295// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000296//
John McCall51fa86f2009-12-02 08:47:38 +0000297// When we process #2, Old contains only the FunctionDecl for #1. By
298// comparing the parameter types, we see that #1 and #2 are overloaded
299// (since they have different signatures), so this routine returns
300// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000301//
John McCall51fa86f2009-12-02 08:47:38 +0000302// When we process #3, Old is an overload set containing #1 and #2. We
303// compare the signatures of #3 to #1 (they're overloaded, so we do
304// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
305// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000306// signature), IsOverload returns false and MatchedDecl will be set to
307// point to the FunctionDecl for #2.
John McCall871b2e72009-12-09 03:35:25 +0000308Sema::OverloadKind
John McCall9f54ad42009-12-10 09:41:52 +0000309Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
310 NamedDecl *&Match) {
John McCall51fa86f2009-12-02 08:47:38 +0000311 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000312 I != E; ++I) {
John McCall51fa86f2009-12-02 08:47:38 +0000313 NamedDecl *OldD = (*I)->getUnderlyingDecl();
314 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall68263142009-11-18 22:49:29 +0000315 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCall871b2e72009-12-09 03:35:25 +0000316 Match = *I;
317 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000318 }
John McCall51fa86f2009-12-02 08:47:38 +0000319 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall68263142009-11-18 22:49:29 +0000320 if (!IsOverload(New, OldF)) {
John McCall871b2e72009-12-09 03:35:25 +0000321 Match = *I;
322 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000323 }
John McCall9f54ad42009-12-10 09:41:52 +0000324 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
325 // We can overload with these, which can show up when doing
326 // redeclaration checks for UsingDecls.
327 assert(Old.getLookupKind() == LookupUsingDeclName);
328 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
329 // Optimistically assume that an unresolved using decl will
330 // overload; if it doesn't, we'll have to diagnose during
331 // template instantiation.
332 } else {
John McCall68263142009-11-18 22:49:29 +0000333 // (C++ 13p1):
334 // Only function declarations can be overloaded; object and type
335 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000336 Match = *I;
337 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000338 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000339 }
John McCall68263142009-11-18 22:49:29 +0000340
John McCall871b2e72009-12-09 03:35:25 +0000341 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000342}
343
344bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
345 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
346 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
347
348 // C++ [temp.fct]p2:
349 // A function template can be overloaded with other function templates
350 // and with normal (non-template) functions.
351 if ((OldTemplate == 0) != (NewTemplate == 0))
352 return true;
353
354 // Is the function New an overload of the function Old?
355 QualType OldQType = Context.getCanonicalType(Old->getType());
356 QualType NewQType = Context.getCanonicalType(New->getType());
357
358 // Compare the signatures (C++ 1.3.10) of the two functions to
359 // determine whether they are overloads. If we find any mismatch
360 // in the signature, they are overloads.
361
362 // If either of these functions is a K&R-style function (no
363 // prototype), then we consider them to have matching signatures.
364 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
365 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
366 return false;
367
368 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
369 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
370
371 // The signature of a function includes the types of its
372 // parameters (C++ 1.3.10), which includes the presence or absence
373 // of the ellipsis; see C++ DR 357).
374 if (OldQType != NewQType &&
375 (OldType->getNumArgs() != NewType->getNumArgs() ||
376 OldType->isVariadic() != NewType->isVariadic() ||
377 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
378 NewType->arg_type_begin())))
379 return true;
380
381 // C++ [temp.over.link]p4:
382 // The signature of a function template consists of its function
383 // signature, its return type and its template parameter list. The names
384 // of the template parameters are significant only for establishing the
385 // relationship between the template parameters and the rest of the
386 // signature.
387 //
388 // We check the return type and template parameter lists for function
389 // templates first; the remaining checks follow.
390 if (NewTemplate &&
391 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
392 OldTemplate->getTemplateParameters(),
393 false, TPL_TemplateMatch) ||
394 OldType->getResultType() != NewType->getResultType()))
395 return true;
396
397 // If the function is a class member, its signature includes the
398 // cv-qualifiers (if any) on the function itself.
399 //
400 // As part of this, also check whether one of the member functions
401 // is static, in which case they are not overloads (C++
402 // 13.1p2). While not part of the definition of the signature,
403 // this check is important to determine whether these functions
404 // can be overloaded.
405 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
406 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
407 if (OldMethod && NewMethod &&
408 !OldMethod->isStatic() && !NewMethod->isStatic() &&
409 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
410 return true;
411
412 // The signatures match; this is not an overload.
413 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000414}
415
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000416/// TryImplicitConversion - Attempt to perform an implicit conversion
417/// from the given expression (Expr) to the given type (ToType). This
418/// function returns an implicit conversion sequence that can be used
419/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000420///
421/// void f(float f);
422/// void g(int i) { f(i); }
423///
424/// this routine would produce an implicit conversion sequence to
425/// describe the initialization of f from i, which will be a standard
426/// conversion sequence containing an lvalue-to-rvalue conversion (C++
427/// 4.1) followed by a floating-integral conversion (C++ 4.9).
428//
429/// Note that this routine only determines how the conversion can be
430/// performed; it does not actually perform the conversion. As such,
431/// it will not produce any diagnostics if no conversion is available,
432/// but will instead return an implicit conversion sequence of kind
433/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000434///
435/// If @p SuppressUserConversions, then user-defined conversions are
436/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000437/// If @p AllowExplicit, then explicit user-defined conversions are
438/// permitted.
Sebastian Redle2b68332009-04-12 17:16:29 +0000439/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
440/// no matter its actual lvalueness.
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000441/// If @p UserCast, the implicit conversion is being done for a user-specified
442/// cast.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000443ImplicitConversionSequence
Anders Carlsson2974b5c2009-08-27 17:14:02 +0000444Sema::TryImplicitConversion(Expr* From, QualType ToType,
445 bool SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +0000446 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000447 bool InOverloadResolution,
448 bool UserCast) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000449 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +0000450 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall1d318332010-01-12 00:44:57 +0000451 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000452 return ICS;
453 }
454
455 if (!getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000456 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000457 return ICS;
458 }
459
460 OverloadCandidateSet Conversions(From->getExprLoc());
461 OverloadingResult UserDefResult
462 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
463 !SuppressUserConversions, AllowExplicit,
464 ForceRValue, UserCast);
465
466 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000467 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000468 // C++ [over.ics.user]p4:
469 // A conversion of an expression of class type to the same class
470 // type is given Exact Match rank, and a conversion of an
471 // expression of class type to a base class of that type is
472 // given Conversion rank, in spite of the fact that a copy
473 // constructor (i.e., a user-defined conversion function) is
474 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000475 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000476 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000477 QualType FromCanon
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000478 = Context.getCanonicalType(From->getType().getUnqualifiedType());
479 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000480 if (Constructor->isCopyConstructor() &&
Douglas Gregor0d6d12b2009-12-22 00:21:20 +0000481 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000482 // Turn this into a "standard" conversion sequence, so that it
483 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000484 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000485 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000486 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000487 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000488 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000489 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000490 ICS.Standard.Second = ICK_Derived_To_Base;
491 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000492 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000493
494 // C++ [over.best.ics]p4:
495 // However, when considering the argument of a user-defined
496 // conversion function that is a candidate by 13.3.1.3 when
497 // invoked for the copying of the temporary in the second step
498 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
499 // 13.3.1.6 in all cases, only standard conversion sequences and
500 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000501 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000502 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000503 }
John McCallcefd3ad2010-01-13 22:30:33 +0000504 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000505 ICS.setAmbiguous();
506 ICS.Ambiguous.setFromType(From->getType());
507 ICS.Ambiguous.setToType(ToType);
508 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
509 Cand != Conversions.end(); ++Cand)
510 if (Cand->Viable)
511 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000512 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000513 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000514 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000515
516 return ICS;
517}
518
Douglas Gregor43c79c22009-12-09 00:47:37 +0000519/// \brief Determine whether the conversion from FromType to ToType is a valid
520/// conversion that strips "noreturn" off the nested function type.
521static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
522 QualType ToType, QualType &ResultTy) {
523 if (Context.hasSameUnqualifiedType(FromType, ToType))
524 return false;
525
526 // Strip the noreturn off the type we're converting from; noreturn can
527 // safely be removed.
528 FromType = Context.getNoReturnType(FromType, false);
529 if (!Context.hasSameUnqualifiedType(FromType, ToType))
530 return false;
531
532 ResultTy = FromType;
533 return true;
534}
535
Douglas Gregor60d62c22008-10-31 16:23:19 +0000536/// IsStandardConversion - Determines whether there is a standard
537/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
538/// expression From to the type ToType. Standard conversion sequences
539/// only consider non-class types; for conversions that involve class
540/// types, use TryImplicitConversion. If a conversion exists, SCS will
541/// contain the standard conversion sequence required to perform this
542/// conversion and this routine will return true. Otherwise, this
543/// routine will return false and the value of SCS is unspecified.
Mike Stump1eb44332009-09-09 15:08:12 +0000544bool
545Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000546 bool InOverloadResolution,
Mike Stump1eb44332009-09-09 15:08:12 +0000547 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000548 QualType FromType = From->getType();
549
Douglas Gregor60d62c22008-10-31 16:23:19 +0000550 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000551 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +0000552 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000553 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +0000554 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000555 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000556
Douglas Gregorf9201e02009-02-11 23:02:49 +0000557 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000558 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000559 if (FromType->isRecordType() || ToType->isRecordType()) {
560 if (getLangOptions().CPlusPlus)
561 return false;
562
Mike Stump1eb44332009-09-09 15:08:12 +0000563 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000564 }
565
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000566 // The first conversion can be an lvalue-to-rvalue conversion,
567 // array-to-pointer conversion, or function-to-pointer conversion
568 // (C++ 4p1).
569
John McCall6bb80172010-03-30 21:47:33 +0000570 DeclAccessPair AccessPair;
571
Mike Stump1eb44332009-09-09 15:08:12 +0000572 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000573 // An lvalue (3.10) of a non-function, non-array type T can be
574 // converted to an rvalue.
575 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000576 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000577 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000578 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000579 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000580
581 // If T is a non-class type, the type of the rvalue is the
582 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000583 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
584 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000585 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000586 } else if (FromType->isArrayType()) {
587 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000588 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000589
590 // An lvalue or rvalue of type "array of N T" or "array of unknown
591 // bound of T" can be converted to an rvalue of type "pointer to
592 // T" (C++ 4.2p1).
593 FromType = Context.getArrayDecayedType(FromType);
594
595 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
596 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +0000597 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000598
599 // For the purpose of ranking in overload resolution
600 // (13.3.3.1.1), this conversion is considered an
601 // array-to-pointer conversion followed by a qualification
602 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000603 SCS.Second = ICK_Identity;
604 SCS.Third = ICK_Qualification;
Douglas Gregorad323a82010-01-27 03:51:04 +0000605 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000606 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000607 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000608 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
609 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000610 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000611
612 // An lvalue of function type T can be converted to an rvalue of
613 // type "pointer to T." The result is a pointer to the
614 // function. (C++ 4.3p1).
615 FromType = Context.getPointerType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000616 } else if (FunctionDecl *Fn
John McCall6bb80172010-03-30 21:47:33 +0000617 = ResolveAddressOfOverloadedFunction(From, ToType, false,
618 AccessPair)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000619 // Address of overloaded function (C++ [over.over]).
Douglas Gregor904eed32008-11-10 20:40:00 +0000620 SCS.First = ICK_Function_To_Pointer;
621
622 // We were able to resolve the address of the overloaded function,
623 // so we can convert to the type of that function.
624 FromType = Fn->getType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000625 if (ToType->isLValueReferenceType())
626 FromType = Context.getLValueReferenceType(FromType);
627 else if (ToType->isRValueReferenceType())
628 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000629 else if (ToType->isMemberPointerType()) {
630 // Resolve address only succeeds if both sides are member pointers,
631 // but it doesn't have to be the same class. See DR 247.
632 // Note that this means that the type of &Derived::fn can be
633 // Ret (Base::*)(Args) if the fn overload actually found is from the
634 // base class, even if it was brought into the derived class via a
635 // using declaration. The standard isn't clear on this issue at all.
636 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
637 FromType = Context.getMemberPointerType(FromType,
638 Context.getTypeDeclType(M->getParent()).getTypePtr());
639 } else
Douglas Gregor904eed32008-11-10 20:40:00 +0000640 FromType = Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000641 } else {
642 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000643 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000644 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000645 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000646
647 // The second conversion can be an integral promotion, floating
648 // point promotion, integral conversion, floating point conversion,
649 // floating-integral conversion, pointer conversion,
650 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000651 // For overloading in C, this can also be a "compatible-type"
652 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000653 bool IncompatibleObjC = false;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000654 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000655 // The unqualified versions of the types are the same: there's no
656 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000657 SCS.Second = ICK_Identity;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000658 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000659 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000660 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000661 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000662 } else if (IsFloatingPointPromotion(FromType, ToType)) {
663 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000664 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000665 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000666 } else if (IsComplexPromotion(FromType, ToType)) {
667 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000668 SCS.Second = ICK_Complex_Promotion;
669 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000670 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000671 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000672 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000673 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000674 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000675 } else if (FromType->isComplexType() && ToType->isComplexType()) {
676 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000677 SCS.Second = ICK_Complex_Conversion;
678 FromType = ToType.getUnqualifiedType();
Chandler Carruth23a370f2010-02-25 07:20:54 +0000679 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
680 (ToType->isComplexType() && FromType->isArithmeticType())) {
681 // Complex-real conversions (C99 6.3.1.7)
682 SCS.Second = ICK_Complex_Real;
683 FromType = ToType.getUnqualifiedType();
684 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
685 // Floating point conversions (C++ 4.8).
686 SCS.Second = ICK_Floating_Conversion;
687 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000688 } else if ((FromType->isFloatingType() &&
689 ToType->isIntegralType() && (!ToType->isBooleanType() &&
690 !ToType->isEnumeralType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000691 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000692 ToType->isFloatingType())) {
693 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000694 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000695 FromType = ToType.getUnqualifiedType();
Anders Carlsson08972922009-08-28 15:33:32 +0000696 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
697 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000698 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000699 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000700 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregorce940492009-09-25 04:25:58 +0000701 } else if (IsMemberPointerConversion(From, FromType, ToType,
702 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000703 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000704 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000705 } else if (ToType->isBooleanType() &&
706 (FromType->isArithmeticType() ||
707 FromType->isEnumeralType() ||
Fariborz Jahanian1f7711d2009-12-11 21:23:13 +0000708 FromType->isAnyPointerType() ||
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000709 FromType->isBlockPointerType() ||
710 FromType->isMemberPointerType() ||
711 FromType->isNullPtrType())) {
712 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000713 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000714 FromType = Context.BoolTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000715 } else if (!getLangOptions().CPlusPlus &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000716 Context.typesAreCompatible(ToType, FromType)) {
717 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000718 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor43c79c22009-12-09 00:47:37 +0000719 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
720 // Treat a conversion that strips "noreturn" as an identity conversion.
721 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000722 } else {
723 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000724 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000725 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000726 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000727
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000728 QualType CanonFrom;
729 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000730 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000731 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000732 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000733 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000734 CanonFrom = Context.getCanonicalType(FromType);
735 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000736 } else {
737 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000738 SCS.Third = ICK_Identity;
739
Mike Stump1eb44332009-09-09 15:08:12 +0000740 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +0000741 // [...] Any difference in top-level cv-qualification is
742 // subsumed by the initialization itself and does not constitute
743 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000744 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000745 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +0000746 if (CanonFrom.getLocalUnqualifiedType()
747 == CanonTo.getLocalUnqualifiedType() &&
748 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000749 FromType = ToType;
750 CanonFrom = CanonTo;
751 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000752 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000753 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000754
755 // If we have not converted the argument type to the parameter type,
756 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000757 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000758 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000759
Douglas Gregor60d62c22008-10-31 16:23:19 +0000760 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000761}
762
763/// IsIntegralPromotion - Determines whether the conversion from the
764/// expression From (whose potentially-adjusted type is FromType) to
765/// ToType is an integral promotion (C++ 4.5). If so, returns true and
766/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000767bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000768 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000769 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000770 if (!To) {
771 return false;
772 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000773
774 // An rvalue of type char, signed char, unsigned char, short int, or
775 // unsigned short int can be converted to an rvalue of type int if
776 // int can represent all the values of the source type; otherwise,
777 // the source rvalue can be converted to an rvalue of type unsigned
778 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +0000779 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
780 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000781 if (// We can promote any signed, promotable integer type to an int
782 (FromType->isSignedIntegerType() ||
783 // We can promote any unsigned integer type whose size is
784 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +0000785 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000786 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000787 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000788 }
789
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000790 return To->getKind() == BuiltinType::UInt;
791 }
792
793 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
794 // can be converted to an rvalue of the first of the following types
795 // that can represent all the values of its underlying type: int,
796 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall842aef82009-12-09 09:09:27 +0000797
798 // We pre-calculate the promotion type for enum types.
799 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
800 if (ToType->isIntegerType())
801 return Context.hasSameUnqualifiedType(ToType,
802 FromEnumType->getDecl()->getPromotionType());
803
804 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000805 // Determine whether the type we're converting from is signed or
806 // unsigned.
807 bool FromIsSigned;
808 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +0000809
810 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
811 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000812
813 // The types we'll try to promote to, in the appropriate
814 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +0000815 QualType PromoteTypes[6] = {
816 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000817 Context.LongTy, Context.UnsignedLongTy ,
818 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000819 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000820 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000821 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
822 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +0000823 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000824 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
825 // We found the type that we can promote to. If this is the
826 // type we wanted, we have a promotion. Otherwise, no
827 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000828 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000829 }
830 }
831 }
832
833 // An rvalue for an integral bit-field (9.6) can be converted to an
834 // rvalue of type int if int can represent all the values of the
835 // bit-field; otherwise, it can be converted to unsigned int if
836 // unsigned int can represent all the values of the bit-field. If
837 // the bit-field is larger yet, no integral promotion applies to
838 // it. If the bit-field has an enumerated type, it is treated as any
839 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +0000840 // FIXME: We should delay checking of bit-fields until we actually perform the
841 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000842 using llvm::APSInt;
843 if (From)
844 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +0000845 APSInt BitWidth;
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000846 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
847 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
848 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
849 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Douglas Gregor86f19402008-12-20 23:49:58 +0000851 // Are we promoting to an int from a bitfield that fits in an int?
852 if (BitWidth < ToSize ||
853 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
854 return To->getKind() == BuiltinType::Int;
855 }
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Douglas Gregor86f19402008-12-20 23:49:58 +0000857 // Are we promoting to an unsigned int from an unsigned bitfield
858 // that fits into an unsigned int?
859 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
860 return To->getKind() == BuiltinType::UInt;
861 }
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Douglas Gregor86f19402008-12-20 23:49:58 +0000863 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000864 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000865 }
Mike Stump1eb44332009-09-09 15:08:12 +0000866
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000867 // An rvalue of type bool can be converted to an rvalue of type int,
868 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000869 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000870 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000871 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000872
873 return false;
874}
875
876/// IsFloatingPointPromotion - Determines whether the conversion from
877/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
878/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000879bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000880 /// An rvalue of type float can be converted to an rvalue of type
881 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +0000882 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
883 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000884 if (FromBuiltin->getKind() == BuiltinType::Float &&
885 ToBuiltin->getKind() == BuiltinType::Double)
886 return true;
887
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000888 // C99 6.3.1.5p1:
889 // When a float is promoted to double or long double, or a
890 // double is promoted to long double [...].
891 if (!getLangOptions().CPlusPlus &&
892 (FromBuiltin->getKind() == BuiltinType::Float ||
893 FromBuiltin->getKind() == BuiltinType::Double) &&
894 (ToBuiltin->getKind() == BuiltinType::LongDouble))
895 return true;
896 }
897
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000898 return false;
899}
900
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000901/// \brief Determine if a conversion is a complex promotion.
902///
903/// A complex promotion is defined as a complex -> complex conversion
904/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000905/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000906bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000907 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000908 if (!FromComplex)
909 return false;
910
John McCall183700f2009-09-21 23:43:11 +0000911 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000912 if (!ToComplex)
913 return false;
914
915 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000916 ToComplex->getElementType()) ||
917 IsIntegralPromotion(0, FromComplex->getElementType(),
918 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000919}
920
Douglas Gregorcb7de522008-11-26 23:31:11 +0000921/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
922/// the pointer type FromPtr to a pointer to type ToPointee, with the
923/// same type qualifiers as FromPtr has on its pointee type. ToType,
924/// if non-empty, will be a pointer to ToType that may or may not have
925/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +0000926static QualType
927BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000928 QualType ToPointee, QualType ToType,
929 ASTContext &Context) {
930 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
931 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +0000932 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +0000933
934 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000935 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +0000936 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +0000937 if (!ToType.isNull())
Douglas Gregorcb7de522008-11-26 23:31:11 +0000938 return ToType;
939
940 // Build a pointer to ToPointee. It has the right qualifiers
941 // already.
942 return Context.getPointerType(ToPointee);
943 }
944
945 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +0000946 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +0000947 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
948 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +0000949}
950
Fariborz Jahanianadcfab12009-12-16 23:13:33 +0000951/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
952/// the FromType, which is an objective-c pointer, to ToType, which may or may
953/// not have the right set of qualifiers.
954static QualType
955BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
956 QualType ToType,
957 ASTContext &Context) {
958 QualType CanonFromType = Context.getCanonicalType(FromType);
959 QualType CanonToType = Context.getCanonicalType(ToType);
960 Qualifiers Quals = CanonFromType.getQualifiers();
961
962 // Exact qualifier match -> return the pointer type we're converting to.
963 if (CanonToType.getLocalQualifiers() == Quals)
964 return ToType;
965
966 // Just build a canonical type that has the right qualifiers.
967 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
968}
969
Mike Stump1eb44332009-09-09 15:08:12 +0000970static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000971 bool InOverloadResolution,
972 ASTContext &Context) {
973 // Handle value-dependent integral null pointer constants correctly.
974 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
975 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
976 Expr->getType()->isIntegralType())
977 return !InOverloadResolution;
978
Douglas Gregorce940492009-09-25 04:25:58 +0000979 return Expr->isNullPointerConstant(Context,
980 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
981 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000982}
Mike Stump1eb44332009-09-09 15:08:12 +0000983
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000984/// IsPointerConversion - Determines whether the conversion of the
985/// expression From, which has the (possibly adjusted) type FromType,
986/// can be converted to the type ToType via a pointer conversion (C++
987/// 4.10). If so, returns true and places the converted type (that
988/// might differ from ToType in its cv-qualifiers at some level) into
989/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000990///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000991/// This routine also supports conversions to and from block pointers
992/// and conversions with Objective-C's 'id', 'id<protocols...>', and
993/// pointers to interfaces. FIXME: Once we've determined the
994/// appropriate overloading rules for Objective-C, we may want to
995/// split the Objective-C checks into a different routine; however,
996/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000997/// conversions, so for now they live here. IncompatibleObjC will be
998/// set if the conversion is an allowed Objective-C conversion that
999/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001000bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001001 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001002 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001003 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001004 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +00001005 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1006 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001007
Mike Stump1eb44332009-09-09 15:08:12 +00001008 // Conversion from a null pointer constant to any Objective-C pointer type.
1009 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001010 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001011 ConvertedType = ToType;
1012 return true;
1013 }
1014
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001015 // Blocks: Block pointers can be converted to void*.
1016 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001017 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001018 ConvertedType = ToType;
1019 return true;
1020 }
1021 // Blocks: A null pointer constant can be converted to a block
1022 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001023 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001024 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001025 ConvertedType = ToType;
1026 return true;
1027 }
1028
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001029 // If the left-hand-side is nullptr_t, the right side can be a null
1030 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001031 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001032 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001033 ConvertedType = ToType;
1034 return true;
1035 }
1036
Ted Kremenek6217b802009-07-29 21:53:49 +00001037 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001038 if (!ToTypePtr)
1039 return false;
1040
1041 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001042 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001043 ConvertedType = ToType;
1044 return true;
1045 }
Sebastian Redl07779722008-10-31 14:43:28 +00001046
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001047 // Beyond this point, both types need to be pointers
1048 // , including objective-c pointers.
1049 QualType ToPointeeType = ToTypePtr->getPointeeType();
1050 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1051 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1052 ToType, Context);
1053 return true;
1054
1055 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001056 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001057 if (!FromTypePtr)
1058 return false;
1059
1060 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001061
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001062 // An rvalue of type "pointer to cv T," where T is an object type,
1063 // can be converted to an rvalue of type "pointer to cv void" (C++
1064 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +00001065 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001066 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001067 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001068 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001069 return true;
1070 }
1071
Douglas Gregorf9201e02009-02-11 23:02:49 +00001072 // When we're overloading in C, we allow a special kind of pointer
1073 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001074 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001075 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001076 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001077 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001078 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001079 return true;
1080 }
1081
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001082 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001083 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001084 // An rvalue of type "pointer to cv D," where D is a class type,
1085 // can be converted to an rvalue of type "pointer to cv B," where
1086 // B is a base class (clause 10) of D. If B is an inaccessible
1087 // (clause 11) or ambiguous (10.2) base class of D, a program that
1088 // necessitates this conversion is ill-formed. The result of the
1089 // conversion is a pointer to the base class sub-object of the
1090 // derived class object. The null pointer value is converted to
1091 // the null pointer value of the destination type.
1092 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001093 // Note that we do not check for ambiguity or inaccessibility
1094 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001095 if (getLangOptions().CPlusPlus &&
1096 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001097 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001098 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001099 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001100 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001101 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001102 ToType, Context);
1103 return true;
1104 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001105
Douglas Gregorc7887512008-12-19 19:13:09 +00001106 return false;
1107}
1108
1109/// isObjCPointerConversion - Determines whether this is an
1110/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1111/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001112bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001113 QualType& ConvertedType,
1114 bool &IncompatibleObjC) {
1115 if (!getLangOptions().ObjC1)
1116 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001117
Steve Naroff14108da2009-07-10 23:34:53 +00001118 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001119 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001120 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001121 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001122
Steve Naroff14108da2009-07-10 23:34:53 +00001123 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001124 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001125 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001126 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001127 ConvertedType = ToType;
1128 return true;
1129 }
1130 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001131 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001132 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001133 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001134 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001135 ConvertedType = ToType;
1136 return true;
1137 }
1138 // Objective C++: We're able to convert from a pointer to an
1139 // interface to a pointer to a different interface.
1140 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001141 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1142 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1143 if (getLangOptions().CPlusPlus && LHS && RHS &&
1144 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1145 FromObjCPtr->getPointeeType()))
1146 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00001147 ConvertedType = ToType;
1148 return true;
1149 }
1150
1151 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1152 // Okay: this is some kind of implicit downcast of Objective-C
1153 // interfaces, which is permitted. However, we're going to
1154 // complain about it.
1155 IncompatibleObjC = true;
1156 ConvertedType = FromType;
1157 return true;
1158 }
Mike Stump1eb44332009-09-09 15:08:12 +00001159 }
Steve Naroff14108da2009-07-10 23:34:53 +00001160 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001161 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001162 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001163 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001164 else if (const BlockPointerType *ToBlockPtr =
1165 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001166 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001167 // to a block pointer type.
1168 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1169 ConvertedType = ToType;
1170 return true;
1171 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001172 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001173 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001174 else if (FromType->getAs<BlockPointerType>() &&
1175 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1176 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001177 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001178 ConvertedType = ToType;
1179 return true;
1180 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001181 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001182 return false;
1183
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001184 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001185 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001186 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001187 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001188 FromPointeeType = FromBlockPtr->getPointeeType();
1189 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001190 return false;
1191
Douglas Gregorc7887512008-12-19 19:13:09 +00001192 // If we have pointers to pointers, recursively check whether this
1193 // is an Objective-C conversion.
1194 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1195 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1196 IncompatibleObjC)) {
1197 // We always complain about this conversion.
1198 IncompatibleObjC = true;
1199 ConvertedType = ToType;
1200 return true;
1201 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001202 // Allow conversion of pointee being objective-c pointer to another one;
1203 // as in I* to id.
1204 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1205 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1206 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1207 IncompatibleObjC)) {
1208 ConvertedType = ToType;
1209 return true;
1210 }
1211
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001212 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001213 // differences in the argument and result types are in Objective-C
1214 // pointer conversions. If so, we permit the conversion (but
1215 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001216 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001217 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001218 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001219 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001220 if (FromFunctionType && ToFunctionType) {
1221 // If the function types are exactly the same, this isn't an
1222 // Objective-C pointer conversion.
1223 if (Context.getCanonicalType(FromPointeeType)
1224 == Context.getCanonicalType(ToPointeeType))
1225 return false;
1226
1227 // Perform the quick checks that will tell us whether these
1228 // function types are obviously different.
1229 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1230 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1231 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1232 return false;
1233
1234 bool HasObjCConversion = false;
1235 if (Context.getCanonicalType(FromFunctionType->getResultType())
1236 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1237 // Okay, the types match exactly. Nothing to do.
1238 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1239 ToFunctionType->getResultType(),
1240 ConvertedType, IncompatibleObjC)) {
1241 // Okay, we have an Objective-C pointer conversion.
1242 HasObjCConversion = true;
1243 } else {
1244 // Function types are too different. Abort.
1245 return false;
1246 }
Mike Stump1eb44332009-09-09 15:08:12 +00001247
Douglas Gregorc7887512008-12-19 19:13:09 +00001248 // Check argument types.
1249 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1250 ArgIdx != NumArgs; ++ArgIdx) {
1251 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1252 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1253 if (Context.getCanonicalType(FromArgType)
1254 == Context.getCanonicalType(ToArgType)) {
1255 // Okay, the types match exactly. Nothing to do.
1256 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1257 ConvertedType, IncompatibleObjC)) {
1258 // Okay, we have an Objective-C pointer conversion.
1259 HasObjCConversion = true;
1260 } else {
1261 // Argument types are too different. Abort.
1262 return false;
1263 }
1264 }
1265
1266 if (HasObjCConversion) {
1267 // We had an Objective-C conversion. Allow this pointer
1268 // conversion, but complain about it.
1269 ConvertedType = ToType;
1270 IncompatibleObjC = true;
1271 return true;
1272 }
1273 }
1274
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001275 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001276}
1277
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001278/// CheckPointerConversion - Check the pointer conversion from the
1279/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001280/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001281/// conversions for which IsPointerConversion has already returned
1282/// true. It returns true and produces a diagnostic if there was an
1283/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001284bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001285 CastExpr::CastKind &Kind,
1286 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001287 QualType FromType = From->getType();
1288
Ted Kremenek6217b802009-07-29 21:53:49 +00001289 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1290 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001291 QualType FromPointeeType = FromPtrType->getPointeeType(),
1292 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001293
Douglas Gregor5fccd362010-03-03 23:55:11 +00001294 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1295 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001296 // We must have a derived-to-base conversion. Check an
1297 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001298 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1299 From->getExprLoc(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001300 From->getSourceRange(),
1301 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001302 return true;
1303
1304 // The conversion was successful.
1305 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001306 }
1307 }
Mike Stump1eb44332009-09-09 15:08:12 +00001308 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001309 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001310 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001311 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001312 // Objective-C++ conversions are always okay.
1313 // FIXME: We should have a different class of conversions for the
1314 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001315 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001316 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001317
Steve Naroff14108da2009-07-10 23:34:53 +00001318 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001319 return false;
1320}
1321
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001322/// IsMemberPointerConversion - Determines whether the conversion of the
1323/// expression From, which has the (possibly adjusted) type FromType, can be
1324/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1325/// If so, returns true and places the converted type (that might differ from
1326/// ToType in its cv-qualifiers at some level) into ConvertedType.
1327bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001328 QualType ToType,
1329 bool InOverloadResolution,
1330 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001331 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001332 if (!ToTypePtr)
1333 return false;
1334
1335 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001336 if (From->isNullPointerConstant(Context,
1337 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1338 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001339 ConvertedType = ToType;
1340 return true;
1341 }
1342
1343 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001344 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001345 if (!FromTypePtr)
1346 return false;
1347
1348 // A pointer to member of B can be converted to a pointer to member of D,
1349 // where D is derived from B (C++ 4.11p2).
1350 QualType FromClass(FromTypePtr->getClass(), 0);
1351 QualType ToClass(ToTypePtr->getClass(), 0);
1352 // FIXME: What happens when these are dependent? Is this function even called?
1353
1354 if (IsDerivedFrom(ToClass, FromClass)) {
1355 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1356 ToClass.getTypePtr());
1357 return true;
1358 }
1359
1360 return false;
1361}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001362
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001363/// CheckMemberPointerConversion - Check the member pointer conversion from the
1364/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00001365/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001366/// for which IsMemberPointerConversion has already returned true. It returns
1367/// true and produces a diagnostic if there was an error, or returns false
1368/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001369bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001370 CastExpr::CastKind &Kind,
1371 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001372 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001373 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001374 if (!FromPtrType) {
1375 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001376 assert(From->isNullPointerConstant(Context,
1377 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001378 "Expr must be null pointer constant!");
1379 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001380 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001381 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001382
Ted Kremenek6217b802009-07-29 21:53:49 +00001383 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001384 assert(ToPtrType && "No member pointer cast has a target type "
1385 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001386
Sebastian Redl21593ac2009-01-28 18:33:18 +00001387 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1388 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001389
Sebastian Redl21593ac2009-01-28 18:33:18 +00001390 // FIXME: What about dependent types?
1391 assert(FromClass->isRecordType() && "Pointer into non-class.");
1392 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001393
John McCall6b2accb2010-02-10 09:31:12 +00001394 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/ true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001395 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001396 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1397 assert(DerivationOkay &&
1398 "Should not have been called if derivation isn't OK.");
1399 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001400
Sebastian Redl21593ac2009-01-28 18:33:18 +00001401 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1402 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001403 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1404 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1405 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1406 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001407 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001408
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001409 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001410 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1411 << FromClass << ToClass << QualType(VBase, 0)
1412 << From->getSourceRange();
1413 return true;
1414 }
1415
John McCall6b2accb2010-02-10 09:31:12 +00001416 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00001417 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1418 Paths.front(),
1419 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00001420
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001421 // Must be a base to derived member conversion.
1422 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001423 return false;
1424}
1425
Douglas Gregor98cd5992008-10-21 23:43:52 +00001426/// IsQualificationConversion - Determines whether the conversion from
1427/// an rvalue of type FromType to ToType is a qualification conversion
1428/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001429bool
1430Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001431 FromType = Context.getCanonicalType(FromType);
1432 ToType = Context.getCanonicalType(ToType);
1433
1434 // If FromType and ToType are the same type, this is not a
1435 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00001436 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00001437 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001438
Douglas Gregor98cd5992008-10-21 23:43:52 +00001439 // (C++ 4.4p4):
1440 // A conversion can add cv-qualifiers at levels other than the first
1441 // in multi-level pointers, subject to the following rules: [...]
1442 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001443 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001444 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001445 // Within each iteration of the loop, we check the qualifiers to
1446 // determine if this still looks like a qualification
1447 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001448 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001449 // until there are no more pointers or pointers-to-members left to
1450 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001451 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001452
1453 // -- for every j > 0, if const is in cv 1,j then const is in cv
1454 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001455 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001456 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001457
Douglas Gregor98cd5992008-10-21 23:43:52 +00001458 // -- if the cv 1,j and cv 2,j are different, then const is in
1459 // every cv for 0 < k < j.
1460 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001461 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001462 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Douglas Gregor98cd5992008-10-21 23:43:52 +00001464 // Keep track of whether all prior cv-qualifiers in the "to" type
1465 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001466 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001467 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001468 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001469
1470 // We are left with FromType and ToType being the pointee types
1471 // after unwrapping the original FromType and ToType the same number
1472 // of types. If we unwrapped any pointers, and if FromType and
1473 // ToType have the same unqualified type (since we checked
1474 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001475 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001476}
1477
Douglas Gregor734d9862009-01-30 23:27:23 +00001478/// Determines whether there is a user-defined conversion sequence
1479/// (C++ [over.ics.user]) that converts expression From to the type
1480/// ToType. If such a conversion exists, User will contain the
1481/// user-defined conversion sequence that performs such a conversion
1482/// and this routine will return true. Otherwise, this routine returns
1483/// false and User is unspecified.
1484///
1485/// \param AllowConversionFunctions true if the conversion should
1486/// consider conversion functions at all. If false, only constructors
1487/// will be considered.
1488///
1489/// \param AllowExplicit true if the conversion should consider C++0x
1490/// "explicit" conversion functions as well as non-explicit conversion
1491/// functions (C++0x [class.conv.fct]p2).
Sebastian Redle2b68332009-04-12 17:16:29 +00001492///
1493/// \param ForceRValue true if the expression should be treated as an rvalue
1494/// for overload resolution.
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001495/// \param UserCast true if looking for user defined conversion for a static
1496/// cast.
Douglas Gregor20093b42009-12-09 23:02:17 +00001497OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1498 UserDefinedConversionSequence& User,
1499 OverloadCandidateSet& CandidateSet,
1500 bool AllowConversionFunctions,
1501 bool AllowExplicit,
1502 bool ForceRValue,
1503 bool UserCast) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001504 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00001505 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1506 // We're not going to find any constructors.
1507 } else if (CXXRecordDecl *ToRecordDecl
1508 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001509 // C++ [over.match.ctor]p1:
1510 // When objects of class type are direct-initialized (8.5), or
1511 // copy-initialized from an expression of the same or a
1512 // derived class type (8.5), overload resolution selects the
1513 // constructor. [...] For copy-initialization, the candidate
1514 // functions are all the converting constructors (12.3.1) of
1515 // that class. The argument list is the expression-list within
1516 // the parentheses of the initializer.
Douglas Gregor79b680e2009-11-13 18:44:21 +00001517 bool SuppressUserConversions = !UserCast;
1518 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1519 IsDerivedFrom(From->getType(), ToType)) {
1520 SuppressUserConversions = false;
1521 AllowConversionFunctions = false;
1522 }
1523
Mike Stump1eb44332009-09-09 15:08:12 +00001524 DeclarationName ConstructorName
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001525 = Context.DeclarationNames.getCXXConstructorName(
1526 Context.getCanonicalType(ToType).getUnqualifiedType());
1527 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump1eb44332009-09-09 15:08:12 +00001528 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001529 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001530 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00001531 NamedDecl *D = *Con;
1532 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1533
Douglas Gregordec06662009-08-21 18:42:58 +00001534 // Find the constructor (which may be a template).
1535 CXXConstructorDecl *Constructor = 0;
1536 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00001537 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00001538 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001539 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001540 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1541 else
John McCall9aa472c2010-03-19 07:35:19 +00001542 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001543
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001544 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001545 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001546 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00001547 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001548 /*ExplicitArgs*/ 0,
John McCalld5532b62009-11-23 01:53:49 +00001549 &From, 1, CandidateSet,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001550 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001551 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001552 // Allow one user-defined conversion when user specifies a
1553 // From->ToType conversion via an static cast (c-style, etc).
John McCall9aa472c2010-03-19 07:35:19 +00001554 AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001555 &From, 1, CandidateSet,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001556 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001557 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001558 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001559 }
1560 }
1561
Douglas Gregor734d9862009-01-30 23:27:23 +00001562 if (!AllowConversionFunctions) {
1563 // Don't allow any conversion functions to enter the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00001564 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1565 PDiag(0)
Anders Carlssonb7906612009-08-26 23:45:07 +00001566 << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001567 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001568 } else if (const RecordType *FromRecordType
Ted Kremenek6217b802009-07-29 21:53:49 +00001569 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001570 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001571 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1572 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00001573 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001574 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001575 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001576 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00001577 DeclAccessPair FoundDecl = I.getPair();
1578 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00001579 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1580 if (isa<UsingShadowDecl>(D))
1581 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1582
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001583 CXXConversionDecl *Conv;
1584 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00001585 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1586 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001587 else
John McCall32daa422010-03-31 01:36:47 +00001588 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001589
1590 if (AllowExplicit || !Conv->isExplicit()) {
1591 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00001592 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001593 ActingContext, From, ToType,
1594 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001595 else
John McCall9aa472c2010-03-19 07:35:19 +00001596 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCall86820f52010-01-26 01:37:31 +00001597 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001598 }
1599 }
1600 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001601 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001602
1603 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001604 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001605 case OR_Success:
1606 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001607 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001608 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1609 // C++ [over.ics.user]p1:
1610 // If the user-defined conversion is specified by a
1611 // constructor (12.3.1), the initial standard conversion
1612 // sequence converts the source type to the type required by
1613 // the argument of the constructor.
1614 //
Douglas Gregor60d62c22008-10-31 16:23:19 +00001615 QualType ThisType = Constructor->getThisType(Context);
John McCall1d318332010-01-12 00:44:57 +00001616 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001617 User.EllipsisConversion = true;
1618 else {
1619 User.Before = Best->Conversions[0].Standard;
1620 User.EllipsisConversion = false;
1621 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001622 User.ConversionFunction = Constructor;
1623 User.After.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00001624 User.After.setFromType(
1625 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregorad323a82010-01-27 03:51:04 +00001626 User.After.setAllToTypes(ToType);
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001627 return OR_Success;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001628 } else if (CXXConversionDecl *Conversion
1629 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1630 // C++ [over.ics.user]p1:
1631 //
1632 // [...] If the user-defined conversion is specified by a
1633 // conversion function (12.3.2), the initial standard
1634 // conversion sequence converts the source type to the
1635 // implicit object parameter of the conversion function.
1636 User.Before = Best->Conversions[0].Standard;
1637 User.ConversionFunction = Conversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001638 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001639
1640 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001641 // The second standard conversion sequence converts the
1642 // result of the user-defined conversion to the target type
1643 // for the sequence. Since an implicit conversion sequence
1644 // is an initialization, the special rules for
1645 // initialization by user-defined conversion apply when
1646 // selecting the best user-defined conversion for a
1647 // user-defined conversion sequence (see 13.3.3 and
1648 // 13.3.3.1).
1649 User.After = Best->FinalConversion;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001650 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001651 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001652 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001653 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001654 }
Mike Stump1eb44332009-09-09 15:08:12 +00001655
Douglas Gregor60d62c22008-10-31 16:23:19 +00001656 case OR_No_Viable_Function:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001657 return OR_No_Viable_Function;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001658 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001659 // No conversion here! We're done.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001660 return OR_Deleted;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001661
1662 case OR_Ambiguous:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001663 return OR_Ambiguous;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001664 }
1665
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001666 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001667}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001668
1669bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001670Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001671 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00001672 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001673 OverloadingResult OvResult =
1674 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1675 CandidateSet, true, false, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001676 if (OvResult == OR_Ambiguous)
1677 Diag(From->getSourceRange().getBegin(),
1678 diag::err_typecheck_ambiguous_condition)
1679 << From->getType() << ToType << From->getSourceRange();
1680 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1681 Diag(From->getSourceRange().getBegin(),
1682 diag::err_typecheck_nonviable_condition)
1683 << From->getType() << ToType << From->getSourceRange();
1684 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001685 return false;
John McCallcbce6062010-01-12 07:18:19 +00001686 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001687 return true;
1688}
Douglas Gregor60d62c22008-10-31 16:23:19 +00001689
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001690/// CompareImplicitConversionSequences - Compare two implicit
1691/// conversion sequences to determine whether one is better than the
1692/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00001693ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001694Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1695 const ImplicitConversionSequence& ICS2)
1696{
1697 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1698 // conversion sequences (as defined in 13.3.3.1)
1699 // -- a standard conversion sequence (13.3.3.1.1) is a better
1700 // conversion sequence than a user-defined conversion sequence or
1701 // an ellipsis conversion sequence, and
1702 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1703 // conversion sequence than an ellipsis conversion sequence
1704 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00001705 //
John McCall1d318332010-01-12 00:44:57 +00001706 // C++0x [over.best.ics]p10:
1707 // For the purpose of ranking implicit conversion sequences as
1708 // described in 13.3.3.2, the ambiguous conversion sequence is
1709 // treated as a user-defined sequence that is indistinguishable
1710 // from any other user-defined conversion sequence.
1711 if (ICS1.getKind() < ICS2.getKind()) {
1712 if (!(ICS1.isUserDefined() && ICS2.isAmbiguous()))
1713 return ImplicitConversionSequence::Better;
1714 } else if (ICS2.getKind() < ICS1.getKind()) {
1715 if (!(ICS2.isUserDefined() && ICS1.isAmbiguous()))
1716 return ImplicitConversionSequence::Worse;
1717 }
1718
1719 if (ICS1.isAmbiguous() || ICS2.isAmbiguous())
1720 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001721
1722 // Two implicit conversion sequences of the same form are
1723 // indistinguishable conversion sequences unless one of the
1724 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00001725 if (ICS1.isStandard())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001726 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00001727 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001728 // User-defined conversion sequence U1 is a better conversion
1729 // sequence than another user-defined conversion sequence U2 if
1730 // they contain the same user-defined conversion function or
1731 // constructor and if the second standard conversion sequence of
1732 // U1 is better than the second standard conversion sequence of
1733 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001734 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001735 ICS2.UserDefined.ConversionFunction)
1736 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1737 ICS2.UserDefined.After);
1738 }
1739
1740 return ImplicitConversionSequence::Indistinguishable;
1741}
1742
Douglas Gregorad323a82010-01-27 03:51:04 +00001743// Per 13.3.3.2p3, compare the given standard conversion sequences to
1744// determine if one is a proper subset of the other.
1745static ImplicitConversionSequence::CompareKind
1746compareStandardConversionSubsets(ASTContext &Context,
1747 const StandardConversionSequence& SCS1,
1748 const StandardConversionSequence& SCS2) {
1749 ImplicitConversionSequence::CompareKind Result
1750 = ImplicitConversionSequence::Indistinguishable;
1751
1752 if (SCS1.Second != SCS2.Second) {
1753 if (SCS1.Second == ICK_Identity)
1754 Result = ImplicitConversionSequence::Better;
1755 else if (SCS2.Second == ICK_Identity)
1756 Result = ImplicitConversionSequence::Worse;
1757 else
1758 return ImplicitConversionSequence::Indistinguishable;
1759 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
1760 return ImplicitConversionSequence::Indistinguishable;
1761
1762 if (SCS1.Third == SCS2.Third) {
1763 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
1764 : ImplicitConversionSequence::Indistinguishable;
1765 }
1766
1767 if (SCS1.Third == ICK_Identity)
1768 return Result == ImplicitConversionSequence::Worse
1769 ? ImplicitConversionSequence::Indistinguishable
1770 : ImplicitConversionSequence::Better;
1771
1772 if (SCS2.Third == ICK_Identity)
1773 return Result == ImplicitConversionSequence::Better
1774 ? ImplicitConversionSequence::Indistinguishable
1775 : ImplicitConversionSequence::Worse;
1776
1777 return ImplicitConversionSequence::Indistinguishable;
1778}
1779
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001780/// CompareStandardConversionSequences - Compare two standard
1781/// conversion sequences to determine whether one is better than the
1782/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001783ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001784Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1785 const StandardConversionSequence& SCS2)
1786{
1787 // Standard conversion sequence S1 is a better conversion sequence
1788 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1789
1790 // -- S1 is a proper subsequence of S2 (comparing the conversion
1791 // sequences in the canonical form defined by 13.3.3.1.1,
1792 // excluding any Lvalue Transformation; the identity conversion
1793 // sequence is considered to be a subsequence of any
1794 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00001795 if (ImplicitConversionSequence::CompareKind CK
1796 = compareStandardConversionSubsets(Context, SCS1, SCS2))
1797 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001798
1799 // -- the rank of S1 is better than the rank of S2 (by the rules
1800 // defined below), or, if not that,
1801 ImplicitConversionRank Rank1 = SCS1.getRank();
1802 ImplicitConversionRank Rank2 = SCS2.getRank();
1803 if (Rank1 < Rank2)
1804 return ImplicitConversionSequence::Better;
1805 else if (Rank2 < Rank1)
1806 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001807
Douglas Gregor57373262008-10-22 14:17:15 +00001808 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1809 // are indistinguishable unless one of the following rules
1810 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00001811
Douglas Gregor57373262008-10-22 14:17:15 +00001812 // A conversion that is not a conversion of a pointer, or
1813 // pointer to member, to bool is better than another conversion
1814 // that is such a conversion.
1815 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1816 return SCS2.isPointerConversionToBool()
1817 ? ImplicitConversionSequence::Better
1818 : ImplicitConversionSequence::Worse;
1819
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001820 // C++ [over.ics.rank]p4b2:
1821 //
1822 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001823 // conversion of B* to A* is better than conversion of B* to
1824 // void*, and conversion of A* to void* is better than conversion
1825 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00001826 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001827 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001828 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001829 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001830 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1831 // Exactly one of the conversion sequences is a conversion to
1832 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001833 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1834 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001835 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1836 // Neither conversion sequence converts to a void pointer; compare
1837 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001838 if (ImplicitConversionSequence::CompareKind DerivedCK
1839 = CompareDerivedToBaseConversions(SCS1, SCS2))
1840 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001841 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1842 // Both conversion sequences are conversions to void
1843 // pointers. Compare the source types to determine if there's an
1844 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00001845 QualType FromType1 = SCS1.getFromType();
1846 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001847
1848 // Adjust the types we're converting from via the array-to-pointer
1849 // conversion, if we need to.
1850 if (SCS1.First == ICK_Array_To_Pointer)
1851 FromType1 = Context.getArrayDecayedType(FromType1);
1852 if (SCS2.First == ICK_Array_To_Pointer)
1853 FromType2 = Context.getArrayDecayedType(FromType2);
1854
Douglas Gregor01919692009-12-13 21:37:05 +00001855 QualType FromPointee1
1856 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1857 QualType FromPointee2
1858 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001859
Douglas Gregor01919692009-12-13 21:37:05 +00001860 if (IsDerivedFrom(FromPointee2, FromPointee1))
1861 return ImplicitConversionSequence::Better;
1862 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1863 return ImplicitConversionSequence::Worse;
1864
1865 // Objective-C++: If one interface is more specific than the
1866 // other, it is the better one.
1867 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1868 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1869 if (FromIface1 && FromIface1) {
1870 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1871 return ImplicitConversionSequence::Better;
1872 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1873 return ImplicitConversionSequence::Worse;
1874 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001875 }
Douglas Gregor57373262008-10-22 14:17:15 +00001876
1877 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1878 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00001879 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001880 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001881 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001882
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001883 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001884 // C++0x [over.ics.rank]p3b4:
1885 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1886 // implicit object parameter of a non-static member function declared
1887 // without a ref-qualifier, and S1 binds an rvalue reference to an
1888 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00001889 // FIXME: We don't know if we're dealing with the implicit object parameter,
1890 // or if the member function in this case has a ref qualifier.
1891 // (Of course, we don't have ref qualifiers yet.)
1892 if (SCS1.RRefBinding != SCS2.RRefBinding)
1893 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1894 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001895
1896 // C++ [over.ics.rank]p3b4:
1897 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1898 // which the references refer are the same type except for
1899 // top-level cv-qualifiers, and the type to which the reference
1900 // initialized by S2 refers is more cv-qualified than the type
1901 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00001902 QualType T1 = SCS1.getToType(2);
1903 QualType T2 = SCS2.getToType(2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001904 T1 = Context.getCanonicalType(T1);
1905 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00001906 Qualifiers T1Quals, T2Quals;
1907 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1908 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1909 if (UnqualT1 == UnqualT2) {
1910 // If the type is an array type, promote the element qualifiers to the type
1911 // for comparison.
1912 if (isa<ArrayType>(T1) && T1Quals)
1913 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1914 if (isa<ArrayType>(T2) && T2Quals)
1915 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001916 if (T2.isMoreQualifiedThan(T1))
1917 return ImplicitConversionSequence::Better;
1918 else if (T1.isMoreQualifiedThan(T2))
1919 return ImplicitConversionSequence::Worse;
1920 }
1921 }
Douglas Gregor57373262008-10-22 14:17:15 +00001922
1923 return ImplicitConversionSequence::Indistinguishable;
1924}
1925
1926/// CompareQualificationConversions - Compares two standard conversion
1927/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00001928/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1929ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00001930Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00001931 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00001932 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001933 // -- S1 and S2 differ only in their qualification conversion and
1934 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1935 // cv-qualification signature of type T1 is a proper subset of
1936 // the cv-qualification signature of type T2, and S1 is not the
1937 // deprecated string literal array-to-pointer conversion (4.2).
1938 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1939 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1940 return ImplicitConversionSequence::Indistinguishable;
1941
1942 // FIXME: the example in the standard doesn't use a qualification
1943 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00001944 QualType T1 = SCS1.getToType(2);
1945 QualType T2 = SCS2.getToType(2);
Douglas Gregor57373262008-10-22 14:17:15 +00001946 T1 = Context.getCanonicalType(T1);
1947 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00001948 Qualifiers T1Quals, T2Quals;
1949 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1950 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00001951
1952 // If the types are the same, we won't learn anything by unwrapped
1953 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00001954 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00001955 return ImplicitConversionSequence::Indistinguishable;
1956
Chandler Carruth28e318c2009-12-29 07:16:59 +00001957 // If the type is an array type, promote the element qualifiers to the type
1958 // for comparison.
1959 if (isa<ArrayType>(T1) && T1Quals)
1960 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1961 if (isa<ArrayType>(T2) && T2Quals)
1962 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1963
Mike Stump1eb44332009-09-09 15:08:12 +00001964 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00001965 = ImplicitConversionSequence::Indistinguishable;
1966 while (UnwrapSimilarPointerTypes(T1, T2)) {
1967 // Within each iteration of the loop, we check the qualifiers to
1968 // determine if this still looks like a qualification
1969 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001970 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001971 // until there are no more pointers or pointers-to-members left
1972 // to unwrap. This essentially mimics what
1973 // IsQualificationConversion does, but here we're checking for a
1974 // strict subset of qualifiers.
1975 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1976 // The qualifiers are the same, so this doesn't tell us anything
1977 // about how the sequences rank.
1978 ;
1979 else if (T2.isMoreQualifiedThan(T1)) {
1980 // T1 has fewer qualifiers, so it could be the better sequence.
1981 if (Result == ImplicitConversionSequence::Worse)
1982 // Neither has qualifiers that are a subset of the other's
1983 // qualifiers.
1984 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Douglas Gregor57373262008-10-22 14:17:15 +00001986 Result = ImplicitConversionSequence::Better;
1987 } else if (T1.isMoreQualifiedThan(T2)) {
1988 // T2 has fewer qualifiers, so it could be the better sequence.
1989 if (Result == ImplicitConversionSequence::Better)
1990 // Neither has qualifiers that are a subset of the other's
1991 // qualifiers.
1992 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Douglas Gregor57373262008-10-22 14:17:15 +00001994 Result = ImplicitConversionSequence::Worse;
1995 } else {
1996 // Qualifiers are disjoint.
1997 return ImplicitConversionSequence::Indistinguishable;
1998 }
1999
2000 // If the types after this point are equivalent, we're done.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002001 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002002 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002003 }
2004
Douglas Gregor57373262008-10-22 14:17:15 +00002005 // Check that the winning standard conversion sequence isn't using
2006 // the deprecated string literal array to pointer conversion.
2007 switch (Result) {
2008 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002009 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002010 Result = ImplicitConversionSequence::Indistinguishable;
2011 break;
2012
2013 case ImplicitConversionSequence::Indistinguishable:
2014 break;
2015
2016 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002017 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002018 Result = ImplicitConversionSequence::Indistinguishable;
2019 break;
2020 }
2021
2022 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002023}
2024
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002025/// CompareDerivedToBaseConversions - Compares two standard conversion
2026/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002027/// various kinds of derived-to-base conversions (C++
2028/// [over.ics.rank]p4b3). As part of these checks, we also look at
2029/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002030ImplicitConversionSequence::CompareKind
2031Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2032 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002033 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002034 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002035 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002036 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002037
2038 // Adjust the types we're converting from via the array-to-pointer
2039 // conversion, if we need to.
2040 if (SCS1.First == ICK_Array_To_Pointer)
2041 FromType1 = Context.getArrayDecayedType(FromType1);
2042 if (SCS2.First == ICK_Array_To_Pointer)
2043 FromType2 = Context.getArrayDecayedType(FromType2);
2044
2045 // Canonicalize all of the types.
2046 FromType1 = Context.getCanonicalType(FromType1);
2047 ToType1 = Context.getCanonicalType(ToType1);
2048 FromType2 = Context.getCanonicalType(FromType2);
2049 ToType2 = Context.getCanonicalType(ToType2);
2050
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002051 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002052 //
2053 // If class B is derived directly or indirectly from class A and
2054 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002055 //
2056 // For Objective-C, we let A, B, and C also be Objective-C
2057 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002058
2059 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002060 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002061 SCS2.Second == ICK_Pointer_Conversion &&
2062 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2063 FromType1->isPointerType() && FromType2->isPointerType() &&
2064 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002065 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002066 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002067 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002068 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002069 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002070 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002071 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002072 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002073
John McCall183700f2009-09-21 23:43:11 +00002074 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2075 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2076 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2077 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002078
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002079 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002080 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2081 if (IsDerivedFrom(ToPointee1, ToPointee2))
2082 return ImplicitConversionSequence::Better;
2083 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2084 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002085
2086 if (ToIface1 && ToIface2) {
2087 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2088 return ImplicitConversionSequence::Better;
2089 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2090 return ImplicitConversionSequence::Worse;
2091 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002092 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002093
2094 // -- conversion of B* to A* is better than conversion of C* to A*,
2095 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2096 if (IsDerivedFrom(FromPointee2, FromPointee1))
2097 return ImplicitConversionSequence::Better;
2098 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2099 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002100
Douglas Gregorcb7de522008-11-26 23:31:11 +00002101 if (FromIface1 && FromIface2) {
2102 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2103 return ImplicitConversionSequence::Better;
2104 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2105 return ImplicitConversionSequence::Worse;
2106 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002107 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002108 }
2109
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002110 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002111 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2112 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2113 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2114 const MemberPointerType * FromMemPointer1 =
2115 FromType1->getAs<MemberPointerType>();
2116 const MemberPointerType * ToMemPointer1 =
2117 ToType1->getAs<MemberPointerType>();
2118 const MemberPointerType * FromMemPointer2 =
2119 FromType2->getAs<MemberPointerType>();
2120 const MemberPointerType * ToMemPointer2 =
2121 ToType2->getAs<MemberPointerType>();
2122 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2123 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2124 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2125 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2126 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2127 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2128 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2129 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002130 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002131 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2132 if (IsDerivedFrom(ToPointee1, ToPointee2))
2133 return ImplicitConversionSequence::Worse;
2134 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2135 return ImplicitConversionSequence::Better;
2136 }
2137 // conversion of B::* to C::* is better than conversion of A::* to C::*
2138 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2139 if (IsDerivedFrom(FromPointee1, FromPointee2))
2140 return ImplicitConversionSequence::Better;
2141 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2142 return ImplicitConversionSequence::Worse;
2143 }
2144 }
2145
Douglas Gregor9e239322010-02-25 19:01:05 +00002146 if ((SCS1.ReferenceBinding || SCS1.CopyConstructor) &&
2147 (SCS2.ReferenceBinding || SCS2.CopyConstructor) &&
Douglas Gregor225c41e2008-11-03 19:09:14 +00002148 SCS1.Second == ICK_Derived_To_Base) {
2149 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00002150 // -- binding of an expression of type C to a reference of type
2151 // B& is better than binding an expression of type C to a
2152 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002153 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2154 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002155 if (IsDerivedFrom(ToType1, ToType2))
2156 return ImplicitConversionSequence::Better;
2157 else if (IsDerivedFrom(ToType2, ToType1))
2158 return ImplicitConversionSequence::Worse;
2159 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002160
Douglas Gregor225c41e2008-11-03 19:09:14 +00002161 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00002162 // -- binding of an expression of type B to a reference of type
2163 // A& is better than binding an expression of type C to a
2164 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002165 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2166 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002167 if (IsDerivedFrom(FromType2, FromType1))
2168 return ImplicitConversionSequence::Better;
2169 else if (IsDerivedFrom(FromType1, FromType2))
2170 return ImplicitConversionSequence::Worse;
2171 }
2172 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002173
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002174 return ImplicitConversionSequence::Indistinguishable;
2175}
2176
Douglas Gregorabe183d2010-04-13 16:31:36 +00002177/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2178/// determine whether they are reference-related,
2179/// reference-compatible, reference-compatible with added
2180/// qualification, or incompatible, for use in C++ initialization by
2181/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2182/// type, and the first type (T1) is the pointee type of the reference
2183/// type being initialized.
2184Sema::ReferenceCompareResult
2185Sema::CompareReferenceRelationship(SourceLocation Loc,
2186 QualType OrigT1, QualType OrigT2,
2187 bool& DerivedToBase) {
2188 assert(!OrigT1->isReferenceType() &&
2189 "T1 must be the pointee type of the reference type");
2190 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2191
2192 QualType T1 = Context.getCanonicalType(OrigT1);
2193 QualType T2 = Context.getCanonicalType(OrigT2);
2194 Qualifiers T1Quals, T2Quals;
2195 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2196 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2197
2198 // C++ [dcl.init.ref]p4:
2199 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2200 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2201 // T1 is a base class of T2.
2202 if (UnqualT1 == UnqualT2)
2203 DerivedToBase = false;
2204 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
2205 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
2206 IsDerivedFrom(UnqualT2, UnqualT1))
2207 DerivedToBase = true;
2208 else
2209 return Ref_Incompatible;
2210
2211 // At this point, we know that T1 and T2 are reference-related (at
2212 // least).
2213
2214 // If the type is an array type, promote the element qualifiers to the type
2215 // for comparison.
2216 if (isa<ArrayType>(T1) && T1Quals)
2217 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2218 if (isa<ArrayType>(T2) && T2Quals)
2219 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2220
2221 // C++ [dcl.init.ref]p4:
2222 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2223 // reference-related to T2 and cv1 is the same cv-qualification
2224 // as, or greater cv-qualification than, cv2. For purposes of
2225 // overload resolution, cases for which cv1 is greater
2226 // cv-qualification than cv2 are identified as
2227 // reference-compatible with added qualification (see 13.3.3.2).
2228 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2229 return Ref_Compatible;
2230 else if (T1.isMoreQualifiedThan(T2))
2231 return Ref_Compatible_With_Added_Qualification;
2232 else
2233 return Ref_Related;
2234}
2235
2236/// \brief Compute an implicit conversion sequence for reference
2237/// initialization.
2238static ImplicitConversionSequence
2239TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2240 SourceLocation DeclLoc,
2241 bool SuppressUserConversions,
2242 bool AllowExplicit, bool ForceRValue) {
2243 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2244
2245 // Most paths end in a failed conversion.
2246 ImplicitConversionSequence ICS;
2247 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2248
2249 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2250 QualType T2 = Init->getType();
2251
2252 // If the initializer is the address of an overloaded function, try
2253 // to resolve the overloaded function. If all goes well, T2 is the
2254 // type of the resulting function.
2255 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2256 DeclAccessPair Found;
2257 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2258 false, Found))
2259 T2 = Fn->getType();
2260 }
2261
2262 // Compute some basic properties of the types and the initializer.
2263 bool isRValRef = DeclType->isRValueReferenceType();
2264 bool DerivedToBase = false;
2265 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2266 Init->isLvalue(S.Context);
2267 Sema::ReferenceCompareResult RefRelationship
2268 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2269
2270 // C++ [dcl.init.ref]p5:
2271 // A reference to type "cv1 T1" is initialized by an expression
2272 // of type "cv2 T2" as follows:
2273
2274 // -- If the initializer expression
2275
2276 // C++ [over.ics.ref]p3:
2277 // Except for an implicit object parameter, for which see 13.3.1,
2278 // a standard conversion sequence cannot be formed if it requires
2279 // binding an lvalue reference to non-const to an rvalue or
2280 // binding an rvalue reference to an lvalue.
2281 if (isRValRef && InitLvalue == Expr::LV_Valid)
2282 return ICS;
2283
2284 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2285 // reference-compatible with "cv2 T2," or
2286 //
2287 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2288 if (InitLvalue == Expr::LV_Valid &&
2289 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2290 // C++ [over.ics.ref]p1:
2291 // When a parameter of reference type binds directly (8.5.3)
2292 // to an argument expression, the implicit conversion sequence
2293 // is the identity conversion, unless the argument expression
2294 // has a type that is a derived class of the parameter type,
2295 // in which case the implicit conversion sequence is a
2296 // derived-to-base Conversion (13.3.3.1).
2297 ICS.setStandard();
2298 ICS.Standard.First = ICK_Identity;
2299 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2300 ICS.Standard.Third = ICK_Identity;
2301 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2302 ICS.Standard.setToType(0, T2);
2303 ICS.Standard.setToType(1, T1);
2304 ICS.Standard.setToType(2, T1);
2305 ICS.Standard.ReferenceBinding = true;
2306 ICS.Standard.DirectBinding = true;
2307 ICS.Standard.RRefBinding = false;
2308 ICS.Standard.CopyConstructor = 0;
2309
2310 // Nothing more to do: the inaccessibility/ambiguity check for
2311 // derived-to-base conversions is suppressed when we're
2312 // computing the implicit conversion sequence (C++
2313 // [over.best.ics]p2).
2314 return ICS;
2315 }
2316
2317 // -- has a class type (i.e., T2 is a class type), where T1 is
2318 // not reference-related to T2, and can be implicitly
2319 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2320 // is reference-compatible with "cv3 T3" 92) (this
2321 // conversion is selected by enumerating the applicable
2322 // conversion functions (13.3.1.6) and choosing the best
2323 // one through overload resolution (13.3)),
2324 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2325 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2326 RefRelationship == Sema::Ref_Incompatible) {
2327 CXXRecordDecl *T2RecordDecl
2328 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2329
2330 OverloadCandidateSet CandidateSet(DeclLoc);
2331 const UnresolvedSetImpl *Conversions
2332 = T2RecordDecl->getVisibleConversionFunctions();
2333 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2334 E = Conversions->end(); I != E; ++I) {
2335 NamedDecl *D = *I;
2336 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2337 if (isa<UsingShadowDecl>(D))
2338 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2339
2340 FunctionTemplateDecl *ConvTemplate
2341 = dyn_cast<FunctionTemplateDecl>(D);
2342 CXXConversionDecl *Conv;
2343 if (ConvTemplate)
2344 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2345 else
2346 Conv = cast<CXXConversionDecl>(D);
2347
2348 // If the conversion function doesn't return a reference type,
2349 // it can't be considered for this conversion.
2350 if (Conv->getConversionType()->isLValueReferenceType() &&
2351 (AllowExplicit || !Conv->isExplicit())) {
2352 if (ConvTemplate)
2353 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2354 Init, DeclType, CandidateSet);
2355 else
2356 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2357 DeclType, CandidateSet);
2358 }
2359 }
2360
2361 OverloadCandidateSet::iterator Best;
2362 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2363 case OR_Success:
2364 // C++ [over.ics.ref]p1:
2365 //
2366 // [...] If the parameter binds directly to the result of
2367 // applying a conversion function to the argument
2368 // expression, the implicit conversion sequence is a
2369 // user-defined conversion sequence (13.3.3.1.2), with the
2370 // second standard conversion sequence either an identity
2371 // conversion or, if the conversion function returns an
2372 // entity of a type that is a derived class of the parameter
2373 // type, a derived-to-base Conversion.
2374 if (!Best->FinalConversion.DirectBinding)
2375 break;
2376
2377 ICS.setUserDefined();
2378 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2379 ICS.UserDefined.After = Best->FinalConversion;
2380 ICS.UserDefined.ConversionFunction = Best->Function;
2381 ICS.UserDefined.EllipsisConversion = false;
2382 assert(ICS.UserDefined.After.ReferenceBinding &&
2383 ICS.UserDefined.After.DirectBinding &&
2384 "Expected a direct reference binding!");
2385 return ICS;
2386
2387 case OR_Ambiguous:
2388 ICS.setAmbiguous();
2389 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2390 Cand != CandidateSet.end(); ++Cand)
2391 if (Cand->Viable)
2392 ICS.Ambiguous.addConversion(Cand->Function);
2393 return ICS;
2394
2395 case OR_No_Viable_Function:
2396 case OR_Deleted:
2397 // There was no suitable conversion, or we found a deleted
2398 // conversion; continue with other checks.
2399 break;
2400 }
2401 }
2402
2403 // -- Otherwise, the reference shall be to a non-volatile const
2404 // type (i.e., cv1 shall be const), or the reference shall be an
2405 // rvalue reference and the initializer expression shall be an rvalue.
2406 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const)
2407 return ICS;
2408
2409 // -- If the initializer expression is an rvalue, with T2 a
2410 // class type, and "cv1 T1" is reference-compatible with
2411 // "cv2 T2," the reference is bound in one of the
2412 // following ways (the choice is implementation-defined):
2413 //
2414 // -- The reference is bound to the object represented by
2415 // the rvalue (see 3.10) or to a sub-object within that
2416 // object.
2417 //
2418 // -- A temporary of type "cv1 T2" [sic] is created, and
2419 // a constructor is called to copy the entire rvalue
2420 // object into the temporary. The reference is bound to
2421 // the temporary or to a sub-object within the
2422 // temporary.
2423 //
2424 // The constructor that would be used to make the copy
2425 // shall be callable whether or not the copy is actually
2426 // done.
2427 //
2428 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
2429 // freedom, so we will always take the first option and never build
2430 // a temporary in this case.
2431 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2432 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2433 ICS.setStandard();
2434 ICS.Standard.First = ICK_Identity;
2435 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2436 ICS.Standard.Third = ICK_Identity;
2437 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2438 ICS.Standard.setToType(0, T2);
2439 ICS.Standard.setToType(1, T1);
2440 ICS.Standard.setToType(2, T1);
2441 ICS.Standard.ReferenceBinding = true;
2442 ICS.Standard.DirectBinding = false;
2443 ICS.Standard.RRefBinding = isRValRef;
2444 ICS.Standard.CopyConstructor = 0;
2445 return ICS;
2446 }
2447
2448 // -- Otherwise, a temporary of type "cv1 T1" is created and
2449 // initialized from the initializer expression using the
2450 // rules for a non-reference copy initialization (8.5). The
2451 // reference is then bound to the temporary. If T1 is
2452 // reference-related to T2, cv1 must be the same
2453 // cv-qualification as, or greater cv-qualification than,
2454 // cv2; otherwise, the program is ill-formed.
2455 if (RefRelationship == Sema::Ref_Related) {
2456 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2457 // we would be reference-compatible or reference-compatible with
2458 // added qualification. But that wasn't the case, so the reference
2459 // initialization fails.
2460 return ICS;
2461 }
2462
2463 // If at least one of the types is a class type, the types are not
2464 // related, and we aren't allowed any user conversions, the
2465 // reference binding fails. This case is important for breaking
2466 // recursion, since TryImplicitConversion below will attempt to
2467 // create a temporary through the use of a copy constructor.
2468 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2469 (T1->isRecordType() || T2->isRecordType()))
2470 return ICS;
2471
2472 // C++ [over.ics.ref]p2:
2473 //
2474 // When a parameter of reference type is not bound directly to
2475 // an argument expression, the conversion sequence is the one
2476 // required to convert the argument expression to the
2477 // underlying type of the reference according to
2478 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2479 // to copy-initializing a temporary of the underlying type with
2480 // the argument expression. Any difference in top-level
2481 // cv-qualification is subsumed by the initialization itself
2482 // and does not constitute a conversion.
2483 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2484 /*AllowExplicit=*/false,
2485 /*ForceRValue=*/false,
2486 /*InOverloadResolution=*/false);
2487
2488 // Of course, that's still a reference binding.
2489 if (ICS.isStandard()) {
2490 ICS.Standard.ReferenceBinding = true;
2491 ICS.Standard.RRefBinding = isRValRef;
2492 } else if (ICS.isUserDefined()) {
2493 ICS.UserDefined.After.ReferenceBinding = true;
2494 ICS.UserDefined.After.RRefBinding = isRValRef;
2495 }
2496 return ICS;
2497}
2498
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002499/// TryCopyInitialization - Try to copy-initialize a value of type
2500/// ToType from the expression From. Return the implicit conversion
2501/// sequence required to pass this argument, which may be a bad
2502/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00002503/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redle2b68332009-04-12 17:16:29 +00002504/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2505/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00002506ImplicitConversionSequence
2507Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002508 bool SuppressUserConversions, bool ForceRValue,
2509 bool InOverloadResolution) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002510 if (ToType->isReferenceType())
2511 return TryReferenceInit(*this, From, ToType,
2512 /*FIXME:*/From->getLocStart(),
2513 SuppressUserConversions,
2514 /*AllowExplicit=*/false,
2515 ForceRValue);
2516
2517 return TryImplicitConversion(From, ToType,
2518 SuppressUserConversions,
2519 /*AllowExplicit=*/false,
2520 ForceRValue,
2521 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002522}
2523
Douglas Gregor96176b32008-11-18 23:14:02 +00002524/// TryObjectArgumentInitialization - Try to initialize the object
2525/// parameter of the given member function (@c Method) from the
2526/// expression @p From.
2527ImplicitConversionSequence
John McCall651f3ee2010-01-14 03:28:57 +00002528Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall701c89e2009-12-03 04:06:58 +00002529 CXXMethodDecl *Method,
2530 CXXRecordDecl *ActingContext) {
2531 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002532 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2533 // const volatile object.
2534 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2535 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2536 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00002537
2538 // Set up the conversion sequence as a "bad" conversion, to allow us
2539 // to exit early.
2540 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00002541
2542 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00002543 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002544 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00002545 FromType = PT->getPointeeType();
2546
2547 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002548
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002549 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00002550 // where X is the class of which the function is a member
2551 // (C++ [over.match.funcs]p4). However, when finding an implicit
2552 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00002553 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00002554 // (C++ [over.match.funcs]p5). We perform a simplified version of
2555 // reference binding here, that allows class rvalues to bind to
2556 // non-constant references.
2557
2558 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2559 // with the implicit object parameter (C++ [over.match.funcs]p5).
2560 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002561 if (ImplicitParamType.getCVRQualifiers()
2562 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00002563 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00002564 ICS.setBad(BadConversionSequence::bad_qualifiers,
2565 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002566 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002567 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002568
2569 // Check that we have either the same type or a derived type. It
2570 // affects the conversion rank.
2571 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00002572 ImplicitConversionKind SecondKind;
2573 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2574 SecondKind = ICK_Identity;
2575 } else if (IsDerivedFrom(FromType, ClassType))
2576 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00002577 else {
John McCallb1bdc622010-02-25 01:37:24 +00002578 ICS.setBad(BadConversionSequence::unrelated_class,
2579 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002580 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002581 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002582
2583 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00002584 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00002585 ICS.Standard.setAsIdentityConversion();
2586 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00002587 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00002588 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002589 ICS.Standard.ReferenceBinding = true;
2590 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00002591 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002592 return ICS;
2593}
2594
2595/// PerformObjectArgumentInitialization - Perform initialization of
2596/// the implicit object parameter for the given Method with the given
2597/// expression.
2598bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00002599Sema::PerformObjectArgumentInitialization(Expr *&From,
2600 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002601 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002602 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002603 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00002604 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00002605 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002606
Ted Kremenek6217b802009-07-29 21:53:49 +00002607 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002608 FromRecordType = PT->getPointeeType();
2609 DestType = Method->getThisType(Context);
2610 } else {
2611 FromRecordType = From->getType();
2612 DestType = ImplicitParamRecordType;
2613 }
2614
John McCall701c89e2009-12-03 04:06:58 +00002615 // Note that we always use the true parent context when performing
2616 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002617 ImplicitConversionSequence ICS
John McCall701c89e2009-12-03 04:06:58 +00002618 = TryObjectArgumentInitialization(From->getType(), Method,
2619 Method->getParent());
John McCall1d318332010-01-12 00:44:57 +00002620 if (ICS.isBad())
Douglas Gregor96176b32008-11-18 23:14:02 +00002621 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002622 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00002623 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002624
Douglas Gregor5fccd362010-03-03 23:55:11 +00002625 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall6bb80172010-03-30 21:47:33 +00002626 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor96176b32008-11-18 23:14:02 +00002627
Douglas Gregor5fccd362010-03-03 23:55:11 +00002628 if (!Context.hasSameType(From->getType(), DestType))
2629 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2630 /*isLvalue=*/!From->getType()->getAs<PointerType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00002631 return false;
2632}
2633
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002634/// TryContextuallyConvertToBool - Attempt to contextually convert the
2635/// expression From to bool (C++0x [conv]p3).
2636ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump1eb44332009-09-09 15:08:12 +00002637 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002638 // FIXME: Are these flags correct?
2639 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00002640 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00002641 /*ForceRValue=*/false,
2642 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002643}
2644
2645/// PerformContextuallyConvertToBool - Perform a contextual conversion
2646/// of the expression From to bool (C++0x [conv]p3).
2647bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2648 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall1d318332010-01-12 00:44:57 +00002649 if (!ICS.isBad())
2650 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002651
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002652 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002653 return Diag(From->getSourceRange().getBegin(),
2654 diag::err_typecheck_bool_condition)
2655 << From->getType() << From->getSourceRange();
2656 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002657}
2658
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002659/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00002660/// candidate functions, using the given function call arguments. If
2661/// @p SuppressUserConversions, then don't allow user-defined
2662/// conversions via constructors or conversion operators.
Sebastian Redle2b68332009-04-12 17:16:29 +00002663/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2664/// hacky way to implement the overloading rules for elidable copy
2665/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002666///
2667/// \para PartialOverloading true if we are performing "partial" overloading
2668/// based on an incomplete set of function arguments. This feature is used by
2669/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00002670void
2671Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002672 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002673 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002674 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00002675 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002676 bool ForceRValue,
2677 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00002678 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002679 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002680 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00002681 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00002682 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00002683
Douglas Gregor88a35142008-12-22 05:46:06 +00002684 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002685 if (!isa<CXXConstructorDecl>(Method)) {
2686 // If we get here, it's because we're calling a member function
2687 // that is named without a member access expression (e.g.,
2688 // "this->f") that was either written explicitly or created
2689 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00002690 // function, e.g., X::f(). We use an empty type for the implied
2691 // object argument (C++ [over.call.func]p3), and the acting context
2692 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00002693 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00002694 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002695 SuppressUserConversions, ForceRValue);
2696 return;
2697 }
2698 // We treat a constructor like a non-member function, since its object
2699 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00002700 }
2701
Douglas Gregorfd476482009-11-13 23:59:09 +00002702 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00002703 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00002704
Douglas Gregor7edfb692009-11-23 12:27:39 +00002705 // Overload resolution is always an unevaluated context.
2706 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2707
Douglas Gregor66724ea2009-11-14 01:20:54 +00002708 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2709 // C++ [class.copy]p3:
2710 // A member function template is never instantiated to perform the copy
2711 // of a class object to an object of its class type.
2712 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2713 if (NumArgs == 1 &&
2714 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor12116062010-02-21 18:30:38 +00002715 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
2716 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00002717 return;
2718 }
2719
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002720 // Add this candidate
2721 CandidateSet.push_back(OverloadCandidate());
2722 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00002723 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002724 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00002725 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002726 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002727 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002728
2729 unsigned NumArgsInProto = Proto->getNumArgs();
2730
2731 // (C++ 13.3.2p2): A candidate function having fewer than m
2732 // parameters is viable only if it has an ellipsis in its parameter
2733 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00002734 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2735 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002736 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002737 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002738 return;
2739 }
2740
2741 // (C++ 13.3.2p2): A candidate function having more than m parameters
2742 // is viable only if the (m+1)st parameter has a default argument
2743 // (8.3.6). For the purposes of overload resolution, the
2744 // parameter list is truncated on the right, so that there are
2745 // exactly m parameters.
2746 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002747 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002748 // Not enough arguments.
2749 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002750 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002751 return;
2752 }
2753
2754 // Determine the implicit conversion sequences for each of the
2755 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002756 Candidate.Conversions.resize(NumArgs);
2757 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2758 if (ArgIdx < NumArgsInProto) {
2759 // (C++ 13.3.2p3): for F to be a viable function, there shall
2760 // exist for each argument an implicit conversion sequence
2761 // (13.3.3.1) that converts that argument to the corresponding
2762 // parameter of F.
2763 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002764 Candidate.Conversions[ArgIdx]
2765 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002766 SuppressUserConversions, ForceRValue,
2767 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00002768 if (Candidate.Conversions[ArgIdx].isBad()) {
2769 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002770 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00002771 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00002772 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002773 } else {
2774 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2775 // argument for which there is no corresponding parameter is
2776 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00002777 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002778 }
2779 }
2780}
2781
Douglas Gregor063daf62009-03-13 18:40:31 +00002782/// \brief Add all of the function declarations in the given function set to
2783/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00002784void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00002785 Expr **Args, unsigned NumArgs,
2786 OverloadCandidateSet& CandidateSet,
2787 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00002788 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00002789 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
2790 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002791 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00002792 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00002793 cast<CXXMethodDecl>(FD)->getParent(),
2794 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00002795 CandidateSet, SuppressUserConversions);
2796 else
John McCall9aa472c2010-03-19 07:35:19 +00002797 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00002798 SuppressUserConversions);
2799 } else {
John McCall9aa472c2010-03-19 07:35:19 +00002800 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00002801 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2802 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00002803 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00002804 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00002805 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00002806 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00002807 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00002808 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00002809 else
John McCall9aa472c2010-03-19 07:35:19 +00002810 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00002811 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00002812 Args, NumArgs, CandidateSet,
2813 SuppressUserConversions);
2814 }
Douglas Gregor364e0212009-06-27 21:05:07 +00002815 }
Douglas Gregor063daf62009-03-13 18:40:31 +00002816}
2817
John McCall314be4e2009-11-17 07:50:12 +00002818/// AddMethodCandidate - Adds a named decl (which is some kind of
2819/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00002820void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00002821 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00002822 Expr **Args, unsigned NumArgs,
2823 OverloadCandidateSet& CandidateSet,
2824 bool SuppressUserConversions, bool ForceRValue) {
John McCall9aa472c2010-03-19 07:35:19 +00002825 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00002826 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00002827
2828 if (isa<UsingShadowDecl>(Decl))
2829 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2830
2831 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2832 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2833 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00002834 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
2835 /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00002836 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00002837 CandidateSet,
2838 SuppressUserConversions,
2839 ForceRValue);
2840 } else {
John McCall9aa472c2010-03-19 07:35:19 +00002841 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00002842 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00002843 CandidateSet, SuppressUserConversions, ForceRValue);
2844 }
2845}
2846
Douglas Gregor96176b32008-11-18 23:14:02 +00002847/// AddMethodCandidate - Adds the given C++ member function to the set
2848/// of candidate functions, using the given function call arguments
2849/// and the object argument (@c Object). For example, in a call
2850/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2851/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2852/// allow user-defined conversions via constructors or conversion
Sebastian Redle2b68332009-04-12 17:16:29 +00002853/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2854/// a slightly hacky way to implement the overloading rules for elidable copy
2855/// initialization in C++0x (C++0x 12.8p15).
Mike Stump1eb44332009-09-09 15:08:12 +00002856void
John McCall9aa472c2010-03-19 07:35:19 +00002857Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002858 CXXRecordDecl *ActingContext, QualType ObjectType,
2859 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00002860 OverloadCandidateSet& CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00002861 bool SuppressUserConversions, bool ForceRValue) {
2862 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002863 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00002864 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002865 assert(!isa<CXXConstructorDecl>(Method) &&
2866 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00002867
Douglas Gregor3f396022009-09-28 04:47:19 +00002868 if (!CandidateSet.isNewCandidate(Method))
2869 return;
2870
Douglas Gregor7edfb692009-11-23 12:27:39 +00002871 // Overload resolution is always an unevaluated context.
2872 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2873
Douglas Gregor96176b32008-11-18 23:14:02 +00002874 // Add this candidate
2875 CandidateSet.push_back(OverloadCandidate());
2876 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00002877 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00002878 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002879 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002880 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002881
2882 unsigned NumArgsInProto = Proto->getNumArgs();
2883
2884 // (C++ 13.3.2p2): A candidate function having fewer than m
2885 // parameters is viable only if it has an ellipsis in its parameter
2886 // list (8.3.5).
2887 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2888 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002889 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00002890 return;
2891 }
2892
2893 // (C++ 13.3.2p2): A candidate function having more than m parameters
2894 // is viable only if the (m+1)st parameter has a default argument
2895 // (8.3.6). For the purposes of overload resolution, the
2896 // parameter list is truncated on the right, so that there are
2897 // exactly m parameters.
2898 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2899 if (NumArgs < MinRequiredArgs) {
2900 // Not enough arguments.
2901 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002902 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00002903 return;
2904 }
2905
2906 Candidate.Viable = true;
2907 Candidate.Conversions.resize(NumArgs + 1);
2908
John McCall701c89e2009-12-03 04:06:58 +00002909 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00002910 // The implicit object argument is ignored.
2911 Candidate.IgnoreObjectArgument = true;
2912 else {
2913 // Determine the implicit conversion sequence for the object
2914 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00002915 Candidate.Conversions[0]
2916 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00002917 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002918 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002919 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00002920 return;
2921 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002922 }
2923
2924 // Determine the implicit conversion sequences for each of the
2925 // arguments.
2926 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2927 if (ArgIdx < NumArgsInProto) {
2928 // (C++ 13.3.2p3): for F to be a viable function, there shall
2929 // exist for each argument an implicit conversion sequence
2930 // (13.3.3.1) that converts that argument to the corresponding
2931 // parameter of F.
2932 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002933 Candidate.Conversions[ArgIdx + 1]
2934 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002935 SuppressUserConversions, ForceRValue,
Anders Carlsson08972922009-08-28 15:33:32 +00002936 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00002937 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002938 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002939 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00002940 break;
2941 }
2942 } else {
2943 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2944 // argument for which there is no corresponding parameter is
2945 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00002946 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00002947 }
2948 }
2949}
2950
Douglas Gregor6b906862009-08-21 00:16:32 +00002951/// \brief Add a C++ member function template as a candidate to the candidate
2952/// set, using template argument deduction to produce an appropriate member
2953/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002954void
Douglas Gregor6b906862009-08-21 00:16:32 +00002955Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00002956 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00002957 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00002958 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00002959 QualType ObjectType,
2960 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002961 OverloadCandidateSet& CandidateSet,
2962 bool SuppressUserConversions,
2963 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002964 if (!CandidateSet.isNewCandidate(MethodTmpl))
2965 return;
2966
Douglas Gregor6b906862009-08-21 00:16:32 +00002967 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002968 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00002969 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002970 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00002971 // candidate functions in the usual way.113) A given name can refer to one
2972 // or more function templates and also to a set of overloaded non-template
2973 // functions. In such a case, the candidate functions generated from each
2974 // function template are combined with the set of non-template candidate
2975 // functions.
John McCall5769d612010-02-08 23:07:23 +00002976 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00002977 FunctionDecl *Specialization = 0;
2978 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00002979 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002980 Args, NumArgs, Specialization, Info)) {
2981 // FIXME: Record what happened with template argument deduction, so
2982 // that we can give the user a beautiful diagnostic.
2983 (void)Result;
2984 return;
2985 }
Mike Stump1eb44332009-09-09 15:08:12 +00002986
Douglas Gregor6b906862009-08-21 00:16:32 +00002987 // Add the function template specialization produced by template argument
2988 // deduction as a candidate.
2989 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00002990 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00002991 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00002992 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002993 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002994 CandidateSet, SuppressUserConversions, ForceRValue);
2995}
2996
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002997/// \brief Add a C++ function template specialization as a candidate
2998/// in the candidate set, using template argument deduction to produce
2999/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003000void
Douglas Gregore53060f2009-06-25 22:08:12 +00003001Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003002 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00003003 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00003004 Expr **Args, unsigned NumArgs,
3005 OverloadCandidateSet& CandidateSet,
3006 bool SuppressUserConversions,
3007 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003008 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3009 return;
3010
Douglas Gregore53060f2009-06-25 22:08:12 +00003011 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003012 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00003013 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003014 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00003015 // candidate functions in the usual way.113) A given name can refer to one
3016 // or more function templates and also to a set of overloaded non-template
3017 // functions. In such a case, the candidate functions generated from each
3018 // function template are combined with the set of non-template candidate
3019 // functions.
John McCall5769d612010-02-08 23:07:23 +00003020 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00003021 FunctionDecl *Specialization = 0;
3022 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003023 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003024 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00003025 CandidateSet.push_back(OverloadCandidate());
3026 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003027 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00003028 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3029 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003030 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00003031 Candidate.IsSurrogate = false;
3032 Candidate.IgnoreObjectArgument = false;
John McCall342fec42010-02-01 18:53:26 +00003033
3034 // TODO: record more information about failed template arguments
3035 Candidate.DeductionFailure.Result = Result;
3036 Candidate.DeductionFailure.TemplateParameter = Info.Param.getOpaqueValue();
Douglas Gregore53060f2009-06-25 22:08:12 +00003037 return;
3038 }
Mike Stump1eb44332009-09-09 15:08:12 +00003039
Douglas Gregore53060f2009-06-25 22:08:12 +00003040 // Add the function template specialization produced by template argument
3041 // deduction as a candidate.
3042 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003043 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregore53060f2009-06-25 22:08:12 +00003044 SuppressUserConversions, ForceRValue);
3045}
Mike Stump1eb44332009-09-09 15:08:12 +00003046
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003047/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00003048/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003049/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00003050/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003051/// (which may or may not be the same type as the type that the
3052/// conversion function produces).
3053void
3054Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003055 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003056 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003057 Expr *From, QualType ToType,
3058 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003059 assert(!Conversion->getDescribedFunctionTemplate() &&
3060 "Conversion function templates use AddTemplateConversionCandidate");
3061
Douglas Gregor3f396022009-09-28 04:47:19 +00003062 if (!CandidateSet.isNewCandidate(Conversion))
3063 return;
3064
Douglas Gregor7edfb692009-11-23 12:27:39 +00003065 // Overload resolution is always an unevaluated context.
3066 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3067
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003068 // Add this candidate
3069 CandidateSet.push_back(OverloadCandidate());
3070 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003071 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003072 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003073 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003074 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003075 Candidate.FinalConversion.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00003076 Candidate.FinalConversion.setFromType(Conversion->getConversionType());
Douglas Gregorad323a82010-01-27 03:51:04 +00003077 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003078
Douglas Gregor96176b32008-11-18 23:14:02 +00003079 // Determine the implicit conversion sequence for the implicit
3080 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003081 Candidate.Viable = true;
3082 Candidate.Conversions.resize(1);
John McCall701c89e2009-12-03 04:06:58 +00003083 Candidate.Conversions[0]
3084 = TryObjectArgumentInitialization(From->getType(), Conversion,
3085 ActingContext);
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00003086 // Conversion functions to a different type in the base class is visible in
3087 // the derived class. So, a derived to base conversion should not participate
3088 // in overload resolution.
3089 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3090 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall1d318332010-01-12 00:44:57 +00003091 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003092 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003093 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003094 return;
3095 }
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003096
3097 // We won't go through a user-define type conversion function to convert a
3098 // derived to base as such conversions are given Conversion Rank. They only
3099 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3100 QualType FromCanon
3101 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3102 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3103 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3104 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003105 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003106 return;
3107 }
3108
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003109
3110 // To determine what the conversion from the result of calling the
3111 // conversion function to the type we're eventually trying to
3112 // convert to (ToType), we need to synthesize a call to the
3113 // conversion function and attempt copy initialization from it. This
3114 // makes sure that we get the right semantics with respect to
3115 // lvalues/rvalues and the type. Fortunately, we can allocate this
3116 // call on the stack and we don't need its arguments to be
3117 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00003118 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003119 From->getLocStart());
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003120 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman73c39ab2009-10-20 08:27:19 +00003121 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003122 &ConversionRef, false);
Mike Stump1eb44332009-09-09 15:08:12 +00003123
3124 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00003125 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3126 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00003127 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003128 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003129 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00003130 ImplicitConversionSequence ICS =
3131 TryCopyInitialization(&Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003132 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003133 /*ForceRValue=*/false,
3134 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003135
John McCall1d318332010-01-12 00:44:57 +00003136 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003137 case ImplicitConversionSequence::StandardConversion:
3138 Candidate.FinalConversion = ICS.Standard;
Douglas Gregorc520c842010-04-12 23:42:09 +00003139
3140 // C++ [over.ics.user]p3:
3141 // If the user-defined conversion is specified by a specialization of a
3142 // conversion function template, the second standard conversion sequence
3143 // shall have exact match rank.
3144 if (Conversion->getPrimaryTemplate() &&
3145 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3146 Candidate.Viable = false;
3147 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3148 }
3149
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003150 break;
3151
3152 case ImplicitConversionSequence::BadConversion:
3153 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003154 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003155 break;
3156
3157 default:
Mike Stump1eb44332009-09-09 15:08:12 +00003158 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003159 "Can only end up with a standard conversion sequence or failure");
3160 }
3161}
3162
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003163/// \brief Adds a conversion function template specialization
3164/// candidate to the overload set, using template argument deduction
3165/// to deduce the template arguments of the conversion function
3166/// template from the type that we are converting to (C++
3167/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00003168void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003169Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003170 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003171 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003172 Expr *From, QualType ToType,
3173 OverloadCandidateSet &CandidateSet) {
3174 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3175 "Only conversion function templates permitted here");
3176
Douglas Gregor3f396022009-09-28 04:47:19 +00003177 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3178 return;
3179
John McCall5769d612010-02-08 23:07:23 +00003180 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003181 CXXConversionDecl *Specialization = 0;
3182 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00003183 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003184 Specialization, Info)) {
3185 // FIXME: Record what happened with template argument deduction, so
3186 // that we can give the user a beautiful diagnostic.
3187 (void)Result;
3188 return;
3189 }
Mike Stump1eb44332009-09-09 15:08:12 +00003190
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003191 // Add the conversion function template specialization produced by
3192 // template argument deduction as a candidate.
3193 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003194 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00003195 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003196}
3197
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003198/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3199/// converts the given @c Object to a function pointer via the
3200/// conversion function @c Conversion, and then attempts to call it
3201/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3202/// the type of function that we'll eventually be calling.
3203void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003204 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003205 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00003206 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00003207 QualType ObjectType,
3208 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003209 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003210 if (!CandidateSet.isNewCandidate(Conversion))
3211 return;
3212
Douglas Gregor7edfb692009-11-23 12:27:39 +00003213 // Overload resolution is always an unevaluated context.
3214 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3215
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003216 CandidateSet.push_back(OverloadCandidate());
3217 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003218 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003219 Candidate.Function = 0;
3220 Candidate.Surrogate = Conversion;
3221 Candidate.Viable = true;
3222 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003223 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003224 Candidate.Conversions.resize(NumArgs + 1);
3225
3226 // Determine the implicit conversion sequence for the implicit
3227 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003228 ImplicitConversionSequence ObjectInit
John McCall701c89e2009-12-03 04:06:58 +00003229 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003230 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003231 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003232 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00003233 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003234 return;
3235 }
3236
3237 // The first conversion is actually a user-defined conversion whose
3238 // first conversion is ObjectInit's standard conversion (which is
3239 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00003240 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003241 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00003242 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003243 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00003244 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003245 = Candidate.Conversions[0].UserDefined.Before;
3246 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3247
Mike Stump1eb44332009-09-09 15:08:12 +00003248 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003249 unsigned NumArgsInProto = Proto->getNumArgs();
3250
3251 // (C++ 13.3.2p2): A candidate function having fewer than m
3252 // parameters is viable only if it has an ellipsis in its parameter
3253 // list (8.3.5).
3254 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3255 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003256 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003257 return;
3258 }
3259
3260 // Function types don't have any default arguments, so just check if
3261 // we have enough arguments.
3262 if (NumArgs < NumArgsInProto) {
3263 // Not enough arguments.
3264 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003265 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003266 return;
3267 }
3268
3269 // Determine the implicit conversion sequences for each of the
3270 // arguments.
3271 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3272 if (ArgIdx < NumArgsInProto) {
3273 // (C++ 13.3.2p3): for F to be a viable function, there shall
3274 // exist for each argument an implicit conversion sequence
3275 // (13.3.3.1) that converts that argument to the corresponding
3276 // parameter of F.
3277 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003278 Candidate.Conversions[ArgIdx + 1]
3279 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003280 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003281 /*ForceRValue=*/false,
3282 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00003283 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003284 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003285 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003286 break;
3287 }
3288 } else {
3289 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3290 // argument for which there is no corresponding parameter is
3291 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003292 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003293 }
3294 }
3295}
3296
Mike Stump390b4cc2009-05-16 07:39:55 +00003297// FIXME: This will eventually be removed, once we've migrated all of the
3298// operator overloading logic over to the scheme used by binary operators, which
3299// works for template instantiation.
Douglas Gregor063daf62009-03-13 18:40:31 +00003300void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00003301 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00003302 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00003303 OverloadCandidateSet& CandidateSet,
3304 SourceRange OpRange) {
John McCall6e266892010-01-26 03:27:55 +00003305 UnresolvedSet<16> Fns;
Douglas Gregor063daf62009-03-13 18:40:31 +00003306
3307 QualType T1 = Args[0]->getType();
3308 QualType T2;
3309 if (NumArgs > 1)
3310 T2 = Args[1]->getType();
3311
3312 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003313 if (S)
John McCall6e266892010-01-26 03:27:55 +00003314 LookupOverloadedOperatorName(Op, S, T1, T2, Fns);
3315 AddFunctionCandidates(Fns, Args, NumArgs, CandidateSet, false);
3316 AddArgumentDependentLookupCandidates(OpName, false, Args, NumArgs, 0,
3317 CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00003318 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregor573d9c32009-10-21 23:19:44 +00003319 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00003320}
3321
3322/// \brief Add overload candidates for overloaded operators that are
3323/// member functions.
3324///
3325/// Add the overloaded operator candidates that are member functions
3326/// for the operator Op that was used in an operator expression such
3327/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3328/// CandidateSet will store the added overload candidates. (C++
3329/// [over.match.oper]).
3330void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3331 SourceLocation OpLoc,
3332 Expr **Args, unsigned NumArgs,
3333 OverloadCandidateSet& CandidateSet,
3334 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003335 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3336
3337 // C++ [over.match.oper]p3:
3338 // For a unary operator @ with an operand of a type whose
3339 // cv-unqualified version is T1, and for a binary operator @ with
3340 // a left operand of a type whose cv-unqualified version is T1 and
3341 // a right operand of a type whose cv-unqualified version is T2,
3342 // three sets of candidate functions, designated member
3343 // candidates, non-member candidates and built-in candidates, are
3344 // constructed as follows:
3345 QualType T1 = Args[0]->getType();
3346 QualType T2;
3347 if (NumArgs > 1)
3348 T2 = Args[1]->getType();
3349
3350 // -- If T1 is a class type, the set of member candidates is the
3351 // result of the qualified lookup of T1::operator@
3352 // (13.3.1.1.1); otherwise, the set of member candidates is
3353 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00003354 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003355 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003356 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003357 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003358
John McCalla24dc2e2009-11-17 02:14:36 +00003359 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3360 LookupQualifiedName(Operators, T1Rec->getDecl());
3361 Operators.suppressDiagnostics();
3362
Mike Stump1eb44332009-09-09 15:08:12 +00003363 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003364 OperEnd = Operators.end();
3365 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00003366 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00003367 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00003368 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00003369 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00003370 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003371}
3372
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003373/// AddBuiltinCandidate - Add a candidate for a built-in
3374/// operator. ResultTy and ParamTys are the result and parameter types
3375/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003376/// arguments being passed to the candidate. IsAssignmentOperator
3377/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003378/// operator. NumContextualBoolArguments is the number of arguments
3379/// (at the beginning of the argument list) that will be contextually
3380/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00003381void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003382 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003383 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003384 bool IsAssignmentOperator,
3385 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00003386 // Overload resolution is always an unevaluated context.
3387 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3388
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003389 // Add this candidate
3390 CandidateSet.push_back(OverloadCandidate());
3391 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003392 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003393 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003394 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003395 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003396 Candidate.BuiltinTypes.ResultTy = ResultTy;
3397 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3398 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3399
3400 // Determine the implicit conversion sequences for each of the
3401 // arguments.
3402 Candidate.Viable = true;
3403 Candidate.Conversions.resize(NumArgs);
3404 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003405 // C++ [over.match.oper]p4:
3406 // For the built-in assignment operators, conversions of the
3407 // left operand are restricted as follows:
3408 // -- no temporaries are introduced to hold the left operand, and
3409 // -- no user-defined conversions are applied to the left
3410 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00003411 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003412 //
3413 // We block these conversions by turning off user-defined
3414 // conversions, since that is the only way that initialization of
3415 // a reference to a non-class type can occur from something that
3416 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003417 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00003418 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003419 "Contextual conversion to bool requires bool type");
3420 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3421 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003422 Candidate.Conversions[ArgIdx]
3423 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00003424 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003425 /*ForceRValue=*/false,
3426 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003427 }
John McCall1d318332010-01-12 00:44:57 +00003428 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003429 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003430 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003431 break;
3432 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003433 }
3434}
3435
3436/// BuiltinCandidateTypeSet - A set of types that will be used for the
3437/// candidate operator functions for built-in operators (C++
3438/// [over.built]). The types are separated into pointer types and
3439/// enumeration types.
3440class BuiltinCandidateTypeSet {
3441 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003442 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003443
3444 /// PointerTypes - The set of pointer types that will be used in the
3445 /// built-in candidates.
3446 TypeSet PointerTypes;
3447
Sebastian Redl78eb8742009-04-19 21:53:20 +00003448 /// MemberPointerTypes - The set of member pointer types that will be
3449 /// used in the built-in candidates.
3450 TypeSet MemberPointerTypes;
3451
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003452 /// EnumerationTypes - The set of enumeration types that will be
3453 /// used in the built-in candidates.
3454 TypeSet EnumerationTypes;
3455
Douglas Gregor5842ba92009-08-24 15:23:48 +00003456 /// Sema - The semantic analysis instance where we are building the
3457 /// candidate type set.
3458 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003459
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003460 /// Context - The AST context in which we will build the type sets.
3461 ASTContext &Context;
3462
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003463 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3464 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00003465 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003466
3467public:
3468 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003469 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003470
Mike Stump1eb44332009-09-09 15:08:12 +00003471 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00003472 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003473
Douglas Gregor573d9c32009-10-21 23:19:44 +00003474 void AddTypesConvertedFrom(QualType Ty,
3475 SourceLocation Loc,
3476 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003477 bool AllowExplicitConversions,
3478 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003479
3480 /// pointer_begin - First pointer type found;
3481 iterator pointer_begin() { return PointerTypes.begin(); }
3482
Sebastian Redl78eb8742009-04-19 21:53:20 +00003483 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003484 iterator pointer_end() { return PointerTypes.end(); }
3485
Sebastian Redl78eb8742009-04-19 21:53:20 +00003486 /// member_pointer_begin - First member pointer type found;
3487 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3488
3489 /// member_pointer_end - Past the last member pointer type found;
3490 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3491
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003492 /// enumeration_begin - First enumeration type found;
3493 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3494
Sebastian Redl78eb8742009-04-19 21:53:20 +00003495 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003496 iterator enumeration_end() { return EnumerationTypes.end(); }
3497};
3498
Sebastian Redl78eb8742009-04-19 21:53:20 +00003499/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003500/// the set of pointer types along with any more-qualified variants of
3501/// that type. For example, if @p Ty is "int const *", this routine
3502/// will add "int const *", "int const volatile *", "int const
3503/// restrict *", and "int const volatile restrict *" to the set of
3504/// pointer types. Returns true if the add of @p Ty itself succeeded,
3505/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003506///
3507/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003508bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00003509BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3510 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00003511
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003512 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003513 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003514 return false;
3515
John McCall0953e762009-09-24 19:53:00 +00003516 const PointerType *PointerTy = Ty->getAs<PointerType>();
3517 assert(PointerTy && "type was not a pointer type!");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003518
John McCall0953e762009-09-24 19:53:00 +00003519 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003520 // Don't add qualified variants of arrays. For one, they're not allowed
3521 // (the qualifier would sink to the element type), and for another, the
3522 // only overload situation where it matters is subscript or pointer +- int,
3523 // and those shouldn't have qualifier variants anyway.
3524 if (PointeeTy->isArrayType())
3525 return true;
John McCall0953e762009-09-24 19:53:00 +00003526 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00003527 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00003528 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003529 bool hasVolatile = VisibleQuals.hasVolatile();
3530 bool hasRestrict = VisibleQuals.hasRestrict();
3531
John McCall0953e762009-09-24 19:53:00 +00003532 // Iterate through all strict supersets of BaseCVR.
3533 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3534 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003535 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3536 // in the types.
3537 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3538 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00003539 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3540 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003541 }
3542
3543 return true;
3544}
3545
Sebastian Redl78eb8742009-04-19 21:53:20 +00003546/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3547/// to the set of pointer types along with any more-qualified variants of
3548/// that type. For example, if @p Ty is "int const *", this routine
3549/// will add "int const *", "int const volatile *", "int const
3550/// restrict *", and "int const volatile restrict *" to the set of
3551/// pointer types. Returns true if the add of @p Ty itself succeeded,
3552/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003553///
3554/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003555bool
3556BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3557 QualType Ty) {
3558 // Insert this type.
3559 if (!MemberPointerTypes.insert(Ty))
3560 return false;
3561
John McCall0953e762009-09-24 19:53:00 +00003562 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3563 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00003564
John McCall0953e762009-09-24 19:53:00 +00003565 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003566 // Don't add qualified variants of arrays. For one, they're not allowed
3567 // (the qualifier would sink to the element type), and for another, the
3568 // only overload situation where it matters is subscript or pointer +- int,
3569 // and those shouldn't have qualifier variants anyway.
3570 if (PointeeTy->isArrayType())
3571 return true;
John McCall0953e762009-09-24 19:53:00 +00003572 const Type *ClassTy = PointerTy->getClass();
3573
3574 // Iterate through all strict supersets of the pointee type's CVR
3575 // qualifiers.
3576 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3577 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3578 if ((CVR | BaseCVR) != CVR) continue;
3579
3580 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3581 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00003582 }
3583
3584 return true;
3585}
3586
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003587/// AddTypesConvertedFrom - Add each of the types to which the type @p
3588/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00003589/// primarily interested in pointer types and enumeration types. We also
3590/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003591/// AllowUserConversions is true if we should look at the conversion
3592/// functions of a class type, and AllowExplicitConversions if we
3593/// should also include the explicit conversion functions of a class
3594/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003595void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003596BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003597 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003598 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003599 bool AllowExplicitConversions,
3600 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003601 // Only deal with canonical types.
3602 Ty = Context.getCanonicalType(Ty);
3603
3604 // Look through reference types; they aren't part of the type of an
3605 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00003606 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003607 Ty = RefTy->getPointeeType();
3608
3609 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003610 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003611
Sebastian Redla65b5512009-11-05 16:36:20 +00003612 // If we're dealing with an array type, decay to the pointer.
3613 if (Ty->isArrayType())
3614 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3615
Ted Kremenek6217b802009-07-29 21:53:49 +00003616 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003617 QualType PointeeTy = PointerTy->getPointeeType();
3618
3619 // Insert our type, and its more-qualified variants, into the set
3620 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003621 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003622 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00003623 } else if (Ty->isMemberPointerType()) {
3624 // Member pointers are far easier, since the pointee can't be converted.
3625 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3626 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003627 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00003628 EnumerationTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003629 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003630 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003631 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003632 // No conversion functions in incomplete types.
3633 return;
3634 }
Mike Stump1eb44332009-09-09 15:08:12 +00003635
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003636 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00003637 const UnresolvedSetImpl *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00003638 = ClassDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003639 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003640 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00003641 NamedDecl *D = I.getDecl();
3642 if (isa<UsingShadowDecl>(D))
3643 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003644
Mike Stump1eb44332009-09-09 15:08:12 +00003645 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003646 // about which builtin types we can convert to.
John McCall32daa422010-03-31 01:36:47 +00003647 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003648 continue;
3649
John McCall32daa422010-03-31 01:36:47 +00003650 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003651 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003652 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003653 VisibleQuals);
3654 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003655 }
3656 }
3657 }
3658}
3659
Douglas Gregor19b7b152009-08-24 13:43:27 +00003660/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3661/// the volatile- and non-volatile-qualified assignment operators for the
3662/// given type to the candidate set.
3663static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3664 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00003665 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003666 unsigned NumArgs,
3667 OverloadCandidateSet &CandidateSet) {
3668 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00003669
Douglas Gregor19b7b152009-08-24 13:43:27 +00003670 // T& operator=(T&, T)
3671 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3672 ParamTypes[1] = T;
3673 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3674 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003675
Douglas Gregor19b7b152009-08-24 13:43:27 +00003676 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3677 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00003678 ParamTypes[0]
3679 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00003680 ParamTypes[1] = T;
3681 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00003682 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003683 }
3684}
Mike Stump1eb44332009-09-09 15:08:12 +00003685
Sebastian Redl9994a342009-10-25 17:03:50 +00003686/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3687/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003688static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3689 Qualifiers VRQuals;
3690 const RecordType *TyRec;
3691 if (const MemberPointerType *RHSMPType =
3692 ArgExpr->getType()->getAs<MemberPointerType>())
3693 TyRec = cast<RecordType>(RHSMPType->getClass());
3694 else
3695 TyRec = ArgExpr->getType()->getAs<RecordType>();
3696 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003697 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003698 VRQuals.addVolatile();
3699 VRQuals.addRestrict();
3700 return VRQuals;
3701 }
3702
3703 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00003704 if (!ClassDecl->hasDefinition())
3705 return VRQuals;
3706
John McCalleec51cf2010-01-20 00:46:10 +00003707 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00003708 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003709
John McCalleec51cf2010-01-20 00:46:10 +00003710 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003711 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00003712 NamedDecl *D = I.getDecl();
3713 if (isa<UsingShadowDecl>(D))
3714 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3715 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003716 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3717 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3718 CanTy = ResTypeRef->getPointeeType();
3719 // Need to go down the pointer/mempointer chain and add qualifiers
3720 // as see them.
3721 bool done = false;
3722 while (!done) {
3723 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3724 CanTy = ResTypePtr->getPointeeType();
3725 else if (const MemberPointerType *ResTypeMPtr =
3726 CanTy->getAs<MemberPointerType>())
3727 CanTy = ResTypeMPtr->getPointeeType();
3728 else
3729 done = true;
3730 if (CanTy.isVolatileQualified())
3731 VRQuals.addVolatile();
3732 if (CanTy.isRestrictQualified())
3733 VRQuals.addRestrict();
3734 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3735 return VRQuals;
3736 }
3737 }
3738 }
3739 return VRQuals;
3740}
3741
Douglas Gregor74253732008-11-19 15:42:04 +00003742/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3743/// operator overloads to the candidate set (C++ [over.built]), based
3744/// on the operator @p Op and the arguments given. For example, if the
3745/// operator is a binary '+', this routine might add "int
3746/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003747void
Mike Stump1eb44332009-09-09 15:08:12 +00003748Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003749 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00003750 Expr **Args, unsigned NumArgs,
3751 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003752 // The set of "promoted arithmetic types", which are the arithmetic
3753 // types are that preserved by promotion (C++ [over.built]p2). Note
3754 // that the first few of these types are the promoted integral
3755 // types; these types need to be first.
3756 // FIXME: What about complex?
3757 const unsigned FirstIntegralType = 0;
3758 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00003759 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003760 LastPromotedIntegralType = 13;
3761 const unsigned FirstPromotedArithmeticType = 7,
3762 LastPromotedArithmeticType = 16;
3763 const unsigned NumArithmeticTypes = 16;
3764 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00003765 Context.BoolTy, Context.CharTy, Context.WCharTy,
3766// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003767 Context.SignedCharTy, Context.ShortTy,
3768 Context.UnsignedCharTy, Context.UnsignedShortTy,
3769 Context.IntTy, Context.LongTy, Context.LongLongTy,
3770 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3771 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3772 };
Douglas Gregor652371a2009-10-21 22:01:30 +00003773 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3774 "Invalid first promoted integral type");
3775 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3776 == Context.UnsignedLongLongTy &&
3777 "Invalid last promoted integral type");
3778 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3779 "Invalid first promoted arithmetic type");
3780 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3781 == Context.LongDoubleTy &&
3782 "Invalid last promoted arithmetic type");
3783
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003784 // Find all of the types that the arguments can convert to, but only
3785 // if the operator we're looking at has built-in operator candidates
3786 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003787 Qualifiers VisibleTypeConversionsQuals;
3788 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003789 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3790 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3791
Douglas Gregor5842ba92009-08-24 15:23:48 +00003792 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003793 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3794 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00003795 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003796 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00003797 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003798 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor74253732008-11-19 15:42:04 +00003799 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003800 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregor573d9c32009-10-21 23:19:44 +00003801 OpLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003802 true,
3803 (Op == OO_Exclaim ||
3804 Op == OO_AmpAmp ||
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003805 Op == OO_PipePipe),
3806 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003807 }
3808
3809 bool isComparison = false;
3810 switch (Op) {
3811 case OO_None:
3812 case NUM_OVERLOADED_OPERATORS:
3813 assert(false && "Expected an overloaded operator");
3814 break;
3815
Douglas Gregor74253732008-11-19 15:42:04 +00003816 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00003817 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00003818 goto UnaryStar;
3819 else
3820 goto BinaryStar;
3821 break;
3822
3823 case OO_Plus: // '+' is either unary or binary
3824 if (NumArgs == 1)
3825 goto UnaryPlus;
3826 else
3827 goto BinaryPlus;
3828 break;
3829
3830 case OO_Minus: // '-' is either unary or binary
3831 if (NumArgs == 1)
3832 goto UnaryMinus;
3833 else
3834 goto BinaryMinus;
3835 break;
3836
3837 case OO_Amp: // '&' is either unary or binary
3838 if (NumArgs == 1)
3839 goto UnaryAmp;
3840 else
3841 goto BinaryAmp;
3842
3843 case OO_PlusPlus:
3844 case OO_MinusMinus:
3845 // C++ [over.built]p3:
3846 //
3847 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3848 // is either volatile or empty, there exist candidate operator
3849 // functions of the form
3850 //
3851 // VQ T& operator++(VQ T&);
3852 // T operator++(VQ T&, int);
3853 //
3854 // C++ [over.built]p4:
3855 //
3856 // For every pair (T, VQ), where T is an arithmetic type other
3857 // than bool, and VQ is either volatile or empty, there exist
3858 // candidate operator functions of the form
3859 //
3860 // VQ T& operator--(VQ T&);
3861 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00003862 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00003863 Arith < NumArithmeticTypes; ++Arith) {
3864 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00003865 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003866 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00003867
3868 // Non-volatile version.
3869 if (NumArgs == 1)
3870 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3871 else
3872 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003873 // heuristic to reduce number of builtin candidates in the set.
3874 // Add volatile version only if there are conversions to a volatile type.
3875 if (VisibleTypeConversionsQuals.hasVolatile()) {
3876 // Volatile version
3877 ParamTypes[0]
3878 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3879 if (NumArgs == 1)
3880 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3881 else
3882 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3883 }
Douglas Gregor74253732008-11-19 15:42:04 +00003884 }
3885
3886 // C++ [over.built]p5:
3887 //
3888 // For every pair (T, VQ), where T is a cv-qualified or
3889 // cv-unqualified object type, and VQ is either volatile or
3890 // empty, there exist candidate operator functions of the form
3891 //
3892 // T*VQ& operator++(T*VQ&);
3893 // T*VQ& operator--(T*VQ&);
3894 // T* operator++(T*VQ&, int);
3895 // T* operator--(T*VQ&, int);
3896 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3897 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3898 // Skip pointer types that aren't pointers to object types.
Ted Kremenek6217b802009-07-29 21:53:49 +00003899 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00003900 continue;
3901
Mike Stump1eb44332009-09-09 15:08:12 +00003902 QualType ParamTypes[2] = {
3903 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00003904 };
Mike Stump1eb44332009-09-09 15:08:12 +00003905
Douglas Gregor74253732008-11-19 15:42:04 +00003906 // Without volatile
3907 if (NumArgs == 1)
3908 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3909 else
3910 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3911
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003912 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3913 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003914 // With volatile
John McCall0953e762009-09-24 19:53:00 +00003915 ParamTypes[0]
3916 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00003917 if (NumArgs == 1)
3918 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3919 else
3920 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3921 }
3922 }
3923 break;
3924
3925 UnaryStar:
3926 // C++ [over.built]p6:
3927 // For every cv-qualified or cv-unqualified object type T, there
3928 // exist candidate operator functions of the form
3929 //
3930 // T& operator*(T*);
3931 //
3932 // C++ [over.built]p7:
3933 // For every function type T, there exist candidate operator
3934 // functions of the form
3935 // T& operator*(T*);
3936 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3937 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3938 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00003939 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003940 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00003941 &ParamTy, Args, 1, CandidateSet);
3942 }
3943 break;
3944
3945 UnaryPlus:
3946 // C++ [over.built]p8:
3947 // For every type T, there exist candidate operator functions of
3948 // the form
3949 //
3950 // T* operator+(T*);
3951 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3952 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3953 QualType ParamTy = *Ptr;
3954 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3955 }
Mike Stump1eb44332009-09-09 15:08:12 +00003956
Douglas Gregor74253732008-11-19 15:42:04 +00003957 // Fall through
3958
3959 UnaryMinus:
3960 // C++ [over.built]p9:
3961 // For every promoted arithmetic type T, there exist candidate
3962 // operator functions of the form
3963 //
3964 // T operator+(T);
3965 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003966 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00003967 Arith < LastPromotedArithmeticType; ++Arith) {
3968 QualType ArithTy = ArithmeticTypes[Arith];
3969 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3970 }
3971 break;
3972
3973 case OO_Tilde:
3974 // C++ [over.built]p10:
3975 // For every promoted integral type T, there exist candidate
3976 // operator functions of the form
3977 //
3978 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003979 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00003980 Int < LastPromotedIntegralType; ++Int) {
3981 QualType IntTy = ArithmeticTypes[Int];
3982 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3983 }
3984 break;
3985
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003986 case OO_New:
3987 case OO_Delete:
3988 case OO_Array_New:
3989 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003990 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00003991 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003992 break;
3993
3994 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00003995 UnaryAmp:
3996 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003997 // C++ [over.match.oper]p3:
3998 // -- For the operator ',', the unary operator '&', or the
3999 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004000 break;
4001
Douglas Gregor19b7b152009-08-24 13:43:27 +00004002 case OO_EqualEqual:
4003 case OO_ExclaimEqual:
4004 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00004005 // For every pointer to member type T, there exist candidate operator
4006 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00004007 //
4008 // bool operator==(T,T);
4009 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00004010 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00004011 MemPtr = CandidateTypes.member_pointer_begin(),
4012 MemPtrEnd = CandidateTypes.member_pointer_end();
4013 MemPtr != MemPtrEnd;
4014 ++MemPtr) {
4015 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4016 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4017 }
Mike Stump1eb44332009-09-09 15:08:12 +00004018
Douglas Gregor19b7b152009-08-24 13:43:27 +00004019 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00004020
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004021 case OO_Less:
4022 case OO_Greater:
4023 case OO_LessEqual:
4024 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004025 // C++ [over.built]p15:
4026 //
4027 // For every pointer or enumeration type T, there exist
4028 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004029 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004030 // bool operator<(T, T);
4031 // bool operator>(T, T);
4032 // bool operator<=(T, T);
4033 // bool operator>=(T, T);
4034 // bool operator==(T, T);
4035 // bool operator!=(T, T);
4036 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4037 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4038 QualType ParamTypes[2] = { *Ptr, *Ptr };
4039 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4040 }
Mike Stump1eb44332009-09-09 15:08:12 +00004041 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004042 = CandidateTypes.enumeration_begin();
4043 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4044 QualType ParamTypes[2] = { *Enum, *Enum };
4045 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4046 }
4047
4048 // Fall through.
4049 isComparison = true;
4050
Douglas Gregor74253732008-11-19 15:42:04 +00004051 BinaryPlus:
4052 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004053 if (!isComparison) {
4054 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4055
4056 // C++ [over.built]p13:
4057 //
4058 // For every cv-qualified or cv-unqualified object type T
4059 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004060 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004061 // T* operator+(T*, ptrdiff_t);
4062 // T& operator[](T*, ptrdiff_t); [BELOW]
4063 // T* operator-(T*, ptrdiff_t);
4064 // T* operator+(ptrdiff_t, T*);
4065 // T& operator[](ptrdiff_t, T*); [BELOW]
4066 //
4067 // C++ [over.built]p14:
4068 //
4069 // For every T, where T is a pointer to object type, there
4070 // exist candidate operator functions of the form
4071 //
4072 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00004073 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004074 = CandidateTypes.pointer_begin();
4075 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4076 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4077
4078 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4079 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4080
4081 if (Op == OO_Plus) {
4082 // T* operator+(ptrdiff_t, T*);
4083 ParamTypes[0] = ParamTypes[1];
4084 ParamTypes[1] = *Ptr;
4085 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4086 } else {
4087 // ptrdiff_t operator-(T, T);
4088 ParamTypes[1] = *Ptr;
4089 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4090 Args, 2, CandidateSet);
4091 }
4092 }
4093 }
4094 // Fall through
4095
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004096 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00004097 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004098 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004099 // C++ [over.built]p12:
4100 //
4101 // For every pair of promoted arithmetic types L and R, there
4102 // exist candidate operator functions of the form
4103 //
4104 // LR operator*(L, R);
4105 // LR operator/(L, R);
4106 // LR operator+(L, R);
4107 // LR operator-(L, R);
4108 // bool operator<(L, R);
4109 // bool operator>(L, R);
4110 // bool operator<=(L, R);
4111 // bool operator>=(L, R);
4112 // bool operator==(L, R);
4113 // bool operator!=(L, R);
4114 //
4115 // where LR is the result of the usual arithmetic conversions
4116 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004117 //
4118 // C++ [over.built]p24:
4119 //
4120 // For every pair of promoted arithmetic types L and R, there exist
4121 // candidate operator functions of the form
4122 //
4123 // LR operator?(bool, L, R);
4124 //
4125 // where LR is the result of the usual arithmetic conversions
4126 // between types L and R.
4127 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004128 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004129 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004130 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004131 Right < LastPromotedArithmeticType; ++Right) {
4132 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00004133 QualType Result
4134 = isComparison
4135 ? Context.BoolTy
4136 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004137 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4138 }
4139 }
4140 break;
4141
4142 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00004143 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004144 case OO_Caret:
4145 case OO_Pipe:
4146 case OO_LessLess:
4147 case OO_GreaterGreater:
4148 // C++ [over.built]p17:
4149 //
4150 // For every pair of promoted integral types L and R, there
4151 // exist candidate operator functions of the form
4152 //
4153 // LR operator%(L, R);
4154 // LR operator&(L, R);
4155 // LR operator^(L, R);
4156 // LR operator|(L, R);
4157 // L operator<<(L, R);
4158 // L operator>>(L, R);
4159 //
4160 // where LR is the result of the usual arithmetic conversions
4161 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00004162 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004163 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004164 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004165 Right < LastPromotedIntegralType; ++Right) {
4166 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4167 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4168 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00004169 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004170 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4171 }
4172 }
4173 break;
4174
4175 case OO_Equal:
4176 // C++ [over.built]p20:
4177 //
4178 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00004179 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004180 // empty, there exist candidate operator functions of the form
4181 //
4182 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004183 for (BuiltinCandidateTypeSet::iterator
4184 Enum = CandidateTypes.enumeration_begin(),
4185 EnumEnd = CandidateTypes.enumeration_end();
4186 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00004187 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004188 CandidateSet);
4189 for (BuiltinCandidateTypeSet::iterator
4190 MemPtr = CandidateTypes.member_pointer_begin(),
4191 MemPtrEnd = CandidateTypes.member_pointer_end();
4192 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00004193 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004194 CandidateSet);
4195 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004196
4197 case OO_PlusEqual:
4198 case OO_MinusEqual:
4199 // C++ [over.built]p19:
4200 //
4201 // For every pair (T, VQ), where T is any type and VQ is either
4202 // volatile or empty, there exist candidate operator functions
4203 // of the form
4204 //
4205 // T*VQ& operator=(T*VQ&, T*);
4206 //
4207 // C++ [over.built]p21:
4208 //
4209 // For every pair (T, VQ), where T is a cv-qualified or
4210 // cv-unqualified object type and VQ is either volatile or
4211 // empty, there exist candidate operator functions of the form
4212 //
4213 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4214 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4215 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4216 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4217 QualType ParamTypes[2];
4218 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4219
4220 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004221 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004222 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4223 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004224
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004225 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4226 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004227 // volatile version
John McCall0953e762009-09-24 19:53:00 +00004228 ParamTypes[0]
4229 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004230 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4231 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00004232 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004233 }
4234 // Fall through.
4235
4236 case OO_StarEqual:
4237 case OO_SlashEqual:
4238 // C++ [over.built]p18:
4239 //
4240 // For every triple (L, VQ, R), where L is an arithmetic type,
4241 // VQ is either volatile or empty, and R is a promoted
4242 // arithmetic type, there exist candidate operator functions of
4243 // the form
4244 //
4245 // VQ L& operator=(VQ L&, R);
4246 // VQ L& operator*=(VQ L&, R);
4247 // VQ L& operator/=(VQ L&, R);
4248 // VQ L& operator+=(VQ L&, R);
4249 // VQ L& operator-=(VQ L&, R);
4250 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004251 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004252 Right < LastPromotedArithmeticType; ++Right) {
4253 QualType ParamTypes[2];
4254 ParamTypes[1] = ArithmeticTypes[Right];
4255
4256 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004257 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004258 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4259 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004260
4261 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004262 if (VisibleTypeConversionsQuals.hasVolatile()) {
4263 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4264 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4265 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4266 /*IsAssigmentOperator=*/Op == OO_Equal);
4267 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004268 }
4269 }
4270 break;
4271
4272 case OO_PercentEqual:
4273 case OO_LessLessEqual:
4274 case OO_GreaterGreaterEqual:
4275 case OO_AmpEqual:
4276 case OO_CaretEqual:
4277 case OO_PipeEqual:
4278 // C++ [over.built]p22:
4279 //
4280 // For every triple (L, VQ, R), where L is an integral type, VQ
4281 // is either volatile or empty, and R is a promoted integral
4282 // type, there exist candidate operator functions of the form
4283 //
4284 // VQ L& operator%=(VQ L&, R);
4285 // VQ L& operator<<=(VQ L&, R);
4286 // VQ L& operator>>=(VQ L&, R);
4287 // VQ L& operator&=(VQ L&, R);
4288 // VQ L& operator^=(VQ L&, R);
4289 // VQ L& operator|=(VQ L&, R);
4290 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004291 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004292 Right < LastPromotedIntegralType; ++Right) {
4293 QualType ParamTypes[2];
4294 ParamTypes[1] = ArithmeticTypes[Right];
4295
4296 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004297 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004298 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00004299 if (VisibleTypeConversionsQuals.hasVolatile()) {
4300 // Add this built-in operator as a candidate (VQ is 'volatile').
4301 ParamTypes[0] = ArithmeticTypes[Left];
4302 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4303 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4304 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4305 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004306 }
4307 }
4308 break;
4309
Douglas Gregor74253732008-11-19 15:42:04 +00004310 case OO_Exclaim: {
4311 // C++ [over.operator]p23:
4312 //
4313 // There also exist candidate operator functions of the form
4314 //
Mike Stump1eb44332009-09-09 15:08:12 +00004315 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00004316 // bool operator&&(bool, bool); [BELOW]
4317 // bool operator||(bool, bool); [BELOW]
4318 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004319 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4320 /*IsAssignmentOperator=*/false,
4321 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00004322 break;
4323 }
4324
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004325 case OO_AmpAmp:
4326 case OO_PipePipe: {
4327 // C++ [over.operator]p23:
4328 //
4329 // There also exist candidate operator functions of the form
4330 //
Douglas Gregor74253732008-11-19 15:42:04 +00004331 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004332 // bool operator&&(bool, bool);
4333 // bool operator||(bool, bool);
4334 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004335 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4336 /*IsAssignmentOperator=*/false,
4337 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004338 break;
4339 }
4340
4341 case OO_Subscript:
4342 // C++ [over.built]p13:
4343 //
4344 // For every cv-qualified or cv-unqualified object type T there
4345 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004346 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004347 // T* operator+(T*, ptrdiff_t); [ABOVE]
4348 // T& operator[](T*, ptrdiff_t);
4349 // T* operator-(T*, ptrdiff_t); [ABOVE]
4350 // T* operator+(ptrdiff_t, T*); [ABOVE]
4351 // T& operator[](ptrdiff_t, T*);
4352 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4353 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4354 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00004355 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004356 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004357
4358 // T& operator[](T*, ptrdiff_t)
4359 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4360
4361 // T& operator[](ptrdiff_t, T*);
4362 ParamTypes[0] = ParamTypes[1];
4363 ParamTypes[1] = *Ptr;
4364 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4365 }
4366 break;
4367
4368 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004369 // C++ [over.built]p11:
4370 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4371 // C1 is the same type as C2 or is a derived class of C2, T is an object
4372 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4373 // there exist candidate operator functions of the form
4374 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4375 // where CV12 is the union of CV1 and CV2.
4376 {
4377 for (BuiltinCandidateTypeSet::iterator Ptr =
4378 CandidateTypes.pointer_begin();
4379 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4380 QualType C1Ty = (*Ptr);
4381 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004382 QualifierCollector Q1;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004383 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004384 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004385 if (!isa<RecordType>(C1))
4386 continue;
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004387 // heuristic to reduce number of builtin candidates in the set.
4388 // Add volatile/restrict version only if there are conversions to a
4389 // volatile/restrict type.
4390 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4391 continue;
4392 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4393 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004394 }
4395 for (BuiltinCandidateTypeSet::iterator
4396 MemPtr = CandidateTypes.member_pointer_begin(),
4397 MemPtrEnd = CandidateTypes.member_pointer_end();
4398 MemPtr != MemPtrEnd; ++MemPtr) {
4399 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4400 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00004401 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004402 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4403 break;
4404 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4405 // build CV12 T&
4406 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004407 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4408 T.isVolatileQualified())
4409 continue;
4410 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4411 T.isRestrictQualified())
4412 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004413 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004414 QualType ResultTy = Context.getLValueReferenceType(T);
4415 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4416 }
4417 }
4418 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004419 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004420
4421 case OO_Conditional:
4422 // Note that we don't consider the first argument, since it has been
4423 // contextually converted to bool long ago. The candidates below are
4424 // therefore added as binary.
4425 //
4426 // C++ [over.built]p24:
4427 // For every type T, where T is a pointer or pointer-to-member type,
4428 // there exist candidate operator functions of the form
4429 //
4430 // T operator?(bool, T, T);
4431 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004432 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4433 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4434 QualType ParamTypes[2] = { *Ptr, *Ptr };
4435 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4436 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00004437 for (BuiltinCandidateTypeSet::iterator Ptr =
4438 CandidateTypes.member_pointer_begin(),
4439 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4440 QualType ParamTypes[2] = { *Ptr, *Ptr };
4441 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4442 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004443 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004444 }
4445}
4446
Douglas Gregorfa047642009-02-04 00:32:51 +00004447/// \brief Add function candidates found via argument-dependent lookup
4448/// to the set of overloading candidates.
4449///
4450/// This routine performs argument-dependent name lookup based on the
4451/// given function name (which may also be an operator name) and adds
4452/// all of the overload candidates found by ADL to the overload
4453/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00004454void
Douglas Gregorfa047642009-02-04 00:32:51 +00004455Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00004456 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00004457 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00004458 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004459 OverloadCandidateSet& CandidateSet,
4460 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00004461 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00004462
John McCalla113e722010-01-26 06:04:06 +00004463 // FIXME: This approach for uniquing ADL results (and removing
4464 // redundant candidates from the set) relies on pointer-equality,
4465 // which means we need to key off the canonical decl. However,
4466 // always going back to the canonical decl might not get us the
4467 // right set of default arguments. What default arguments are
4468 // we supposed to consider on ADL candidates, anyway?
4469
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004470 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00004471 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00004472
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004473 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004474 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4475 CandEnd = CandidateSet.end();
4476 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00004477 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00004478 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00004479 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00004480 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00004481 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004482
4483 // For each of the ADL candidates we found, add it to the overload
4484 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00004485 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00004486 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00004487 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00004488 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004489 continue;
4490
John McCall9aa472c2010-03-19 07:35:19 +00004491 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004492 false, false, PartialOverloading);
4493 } else
John McCall6e266892010-01-26 03:27:55 +00004494 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00004495 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004496 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00004497 }
Douglas Gregorfa047642009-02-04 00:32:51 +00004498}
4499
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004500/// isBetterOverloadCandidate - Determines whether the first overload
4501/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00004502bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004503Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCall5769d612010-02-08 23:07:23 +00004504 const OverloadCandidate& Cand2,
4505 SourceLocation Loc) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004506 // Define viable functions to be better candidates than non-viable
4507 // functions.
4508 if (!Cand2.Viable)
4509 return Cand1.Viable;
4510 else if (!Cand1.Viable)
4511 return false;
4512
Douglas Gregor88a35142008-12-22 05:46:06 +00004513 // C++ [over.match.best]p1:
4514 //
4515 // -- if F is a static member function, ICS1(F) is defined such
4516 // that ICS1(F) is neither better nor worse than ICS1(G) for
4517 // any function G, and, symmetrically, ICS1(G) is neither
4518 // better nor worse than ICS1(F).
4519 unsigned StartArg = 0;
4520 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4521 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004522
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004523 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00004524 // A viable function F1 is defined to be a better function than another
4525 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004526 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004527 unsigned NumArgs = Cand1.Conversions.size();
4528 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4529 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004530 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004531 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4532 Cand2.Conversions[ArgIdx])) {
4533 case ImplicitConversionSequence::Better:
4534 // Cand1 has a better conversion sequence.
4535 HasBetterConversion = true;
4536 break;
4537
4538 case ImplicitConversionSequence::Worse:
4539 // Cand1 can't be better than Cand2.
4540 return false;
4541
4542 case ImplicitConversionSequence::Indistinguishable:
4543 // Do nothing.
4544 break;
4545 }
4546 }
4547
Mike Stump1eb44332009-09-09 15:08:12 +00004548 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004549 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004550 if (HasBetterConversion)
4551 return true;
4552
Mike Stump1eb44332009-09-09 15:08:12 +00004553 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004554 // specialization, or, if not that,
4555 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4556 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4557 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004558
4559 // -- F1 and F2 are function template specializations, and the function
4560 // template for F1 is more specialized than the template for F2
4561 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004562 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00004563 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4564 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004565 if (FunctionTemplateDecl *BetterTemplate
4566 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4567 Cand2.Function->getPrimaryTemplate(),
John McCall5769d612010-02-08 23:07:23 +00004568 Loc,
Douglas Gregor5d7d3752009-09-14 23:02:14 +00004569 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4570 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004571 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004572
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004573 // -- the context is an initialization by user-defined conversion
4574 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4575 // from the return type of F1 to the destination type (i.e.,
4576 // the type of the entity being initialized) is a better
4577 // conversion sequence than the standard conversion sequence
4578 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00004579 if (Cand1.Function && Cand2.Function &&
4580 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004581 isa<CXXConversionDecl>(Cand2.Function)) {
4582 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4583 Cand2.FinalConversion)) {
4584 case ImplicitConversionSequence::Better:
4585 // Cand1 has a better conversion sequence.
4586 return true;
4587
4588 case ImplicitConversionSequence::Worse:
4589 // Cand1 can't be better than Cand2.
4590 return false;
4591
4592 case ImplicitConversionSequence::Indistinguishable:
4593 // Do nothing
4594 break;
4595 }
4596 }
4597
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004598 return false;
4599}
4600
Mike Stump1eb44332009-09-09 15:08:12 +00004601/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00004602/// within an overload candidate set.
4603///
4604/// \param CandidateSet the set of candidate functions.
4605///
4606/// \param Loc the location of the function name (or operator symbol) for
4607/// which overload resolution occurs.
4608///
Mike Stump1eb44332009-09-09 15:08:12 +00004609/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00004610/// function, Best points to the candidate function found.
4611///
4612/// \returns The result of overload resolution.
Douglas Gregor20093b42009-12-09 23:02:17 +00004613OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4614 SourceLocation Loc,
4615 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004616 // Find the best viable function.
4617 Best = CandidateSet.end();
4618 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4619 Cand != CandidateSet.end(); ++Cand) {
4620 if (Cand->Viable) {
John McCall5769d612010-02-08 23:07:23 +00004621 if (Best == CandidateSet.end() ||
4622 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004623 Best = Cand;
4624 }
4625 }
4626
4627 // If we didn't find any viable functions, abort.
4628 if (Best == CandidateSet.end())
4629 return OR_No_Viable_Function;
4630
4631 // Make sure that this function is better than every other viable
4632 // function. If not, we have an ambiguity.
4633 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4634 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00004635 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004636 Cand != Best &&
John McCall5769d612010-02-08 23:07:23 +00004637 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004638 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004639 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004640 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004641 }
Mike Stump1eb44332009-09-09 15:08:12 +00004642
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004643 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004644 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00004645 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004646 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004647 return OR_Deleted;
4648
Douglas Gregore0762c92009-06-19 23:52:42 +00004649 // C++ [basic.def.odr]p2:
4650 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00004651 // when referred to from a potentially-evaluated expression. [Note: this
4652 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00004653 // (clause 13), user-defined conversions (12.3.2), allocation function for
4654 // placement new (5.3.4), as well as non-default initialization (8.5).
4655 if (Best->Function)
4656 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004657 return OR_Success;
4658}
4659
John McCall3c80f572010-01-12 02:15:36 +00004660namespace {
4661
4662enum OverloadCandidateKind {
4663 oc_function,
4664 oc_method,
4665 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00004666 oc_function_template,
4667 oc_method_template,
4668 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00004669 oc_implicit_default_constructor,
4670 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00004671 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00004672};
4673
John McCall220ccbf2010-01-13 00:25:19 +00004674OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4675 FunctionDecl *Fn,
4676 std::string &Description) {
4677 bool isTemplate = false;
4678
4679 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4680 isTemplate = true;
4681 Description = S.getTemplateArgumentBindingsText(
4682 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4683 }
John McCallb1622a12010-01-06 09:43:14 +00004684
4685 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00004686 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00004687 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00004688
John McCall3c80f572010-01-12 02:15:36 +00004689 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4690 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00004691 }
4692
4693 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4694 // This actually gets spelled 'candidate function' for now, but
4695 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00004696 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00004697 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00004698
4699 assert(Meth->isCopyAssignment()
4700 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00004701 return oc_implicit_copy_assignment;
4702 }
4703
John McCall220ccbf2010-01-13 00:25:19 +00004704 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00004705}
4706
4707} // end anonymous namespace
4708
4709// Notes the location of an overload candidate.
4710void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00004711 std::string FnDesc;
4712 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4713 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4714 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00004715}
4716
John McCall1d318332010-01-12 00:44:57 +00004717/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4718/// "lead" diagnostic; it will be given two arguments, the source and
4719/// target types of the conversion.
4720void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4721 SourceLocation CaretLoc,
4722 const PartialDiagnostic &PDiag) {
4723 Diag(CaretLoc, PDiag)
4724 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4725 for (AmbiguousConversionSequence::const_iterator
4726 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4727 NoteOverloadCandidate(*I);
4728 }
John McCall81201622010-01-08 04:41:39 +00004729}
4730
John McCall1d318332010-01-12 00:44:57 +00004731namespace {
4732
John McCalladbb8f82010-01-13 09:16:55 +00004733void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4734 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4735 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00004736 assert(Cand->Function && "for now, candidate must be a function");
4737 FunctionDecl *Fn = Cand->Function;
4738
4739 // There's a conversion slot for the object argument if this is a
4740 // non-constructor method. Note that 'I' corresponds the
4741 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00004742 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00004743 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00004744 if (I == 0)
4745 isObjectArgument = true;
4746 else
4747 I--;
John McCall220ccbf2010-01-13 00:25:19 +00004748 }
4749
John McCall220ccbf2010-01-13 00:25:19 +00004750 std::string FnDesc;
4751 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4752
John McCalladbb8f82010-01-13 09:16:55 +00004753 Expr *FromExpr = Conv.Bad.FromExpr;
4754 QualType FromTy = Conv.Bad.getFromType();
4755 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00004756
John McCall5920dbb2010-02-02 02:42:52 +00004757 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00004758 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00004759 Expr *E = FromExpr->IgnoreParens();
4760 if (isa<UnaryOperator>(E))
4761 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00004762 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00004763
4764 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
4765 << (unsigned) FnKind << FnDesc
4766 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4767 << ToTy << Name << I+1;
4768 return;
4769 }
4770
John McCall258b2032010-01-23 08:10:49 +00004771 // Do some hand-waving analysis to see if the non-viability is due
4772 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00004773 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4774 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4775 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4776 CToTy = RT->getPointeeType();
4777 else {
4778 // TODO: detect and diagnose the full richness of const mismatches.
4779 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4780 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4781 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4782 }
4783
4784 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4785 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4786 // It is dumb that we have to do this here.
4787 while (isa<ArrayType>(CFromTy))
4788 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4789 while (isa<ArrayType>(CToTy))
4790 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4791
4792 Qualifiers FromQs = CFromTy.getQualifiers();
4793 Qualifiers ToQs = CToTy.getQualifiers();
4794
4795 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4796 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4797 << (unsigned) FnKind << FnDesc
4798 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4799 << FromTy
4800 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4801 << (unsigned) isObjectArgument << I+1;
4802 return;
4803 }
4804
4805 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4806 assert(CVR && "unexpected qualifiers mismatch");
4807
4808 if (isObjectArgument) {
4809 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4810 << (unsigned) FnKind << FnDesc
4811 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4812 << FromTy << (CVR - 1);
4813 } else {
4814 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4815 << (unsigned) FnKind << FnDesc
4816 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4817 << FromTy << (CVR - 1) << I+1;
4818 }
4819 return;
4820 }
4821
John McCall258b2032010-01-23 08:10:49 +00004822 // Diagnose references or pointers to incomplete types differently,
4823 // since it's far from impossible that the incompleteness triggered
4824 // the failure.
4825 QualType TempFromTy = FromTy.getNonReferenceType();
4826 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
4827 TempFromTy = PTy->getPointeeType();
4828 if (TempFromTy->isIncompleteType()) {
4829 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
4830 << (unsigned) FnKind << FnDesc
4831 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4832 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4833 return;
4834 }
4835
John McCall651f3ee2010-01-14 03:28:57 +00004836 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00004837 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4838 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00004839 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00004840 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00004841}
4842
4843void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4844 unsigned NumFormalArgs) {
4845 // TODO: treat calls to a missing default constructor as a special case
4846
4847 FunctionDecl *Fn = Cand->Function;
4848 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4849
4850 unsigned MinParams = Fn->getMinRequiredArguments();
4851
4852 // at least / at most / exactly
4853 unsigned mode, modeCount;
4854 if (NumFormalArgs < MinParams) {
4855 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4856 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4857 mode = 0; // "at least"
4858 else
4859 mode = 2; // "exactly"
4860 modeCount = MinParams;
4861 } else {
4862 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4863 if (MinParams != FnTy->getNumArgs())
4864 mode = 1; // "at most"
4865 else
4866 mode = 2; // "exactly"
4867 modeCount = FnTy->getNumArgs();
4868 }
4869
4870 std::string Description;
4871 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4872
4873 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4874 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00004875}
4876
John McCall342fec42010-02-01 18:53:26 +00004877/// Diagnose a failed template-argument deduction.
4878void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
4879 Expr **Args, unsigned NumArgs) {
4880 FunctionDecl *Fn = Cand->Function; // pattern
4881
4882 TemplateParameter Param = TemplateParameter::getFromOpaqueValue(
4883 Cand->DeductionFailure.TemplateParameter);
4884
4885 switch (Cand->DeductionFailure.Result) {
4886 case Sema::TDK_Success:
4887 llvm_unreachable("TDK_success while diagnosing bad deduction");
4888
4889 case Sema::TDK_Incomplete: {
4890 NamedDecl *ParamD;
4891 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
4892 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
4893 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
4894 assert(ParamD && "no parameter found for incomplete deduction result");
4895 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
4896 << ParamD->getDeclName();
4897 return;
4898 }
4899
4900 // TODO: diagnose these individually, then kill off
4901 // note_ovl_candidate_bad_deduction, which is uselessly vague.
4902 case Sema::TDK_InstantiationDepth:
4903 case Sema::TDK_Inconsistent:
4904 case Sema::TDK_InconsistentQuals:
4905 case Sema::TDK_SubstitutionFailure:
4906 case Sema::TDK_NonDeducedMismatch:
4907 case Sema::TDK_TooManyArguments:
4908 case Sema::TDK_TooFewArguments:
4909 case Sema::TDK_InvalidExplicitArguments:
4910 case Sema::TDK_FailedOverloadResolution:
4911 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
4912 return;
4913 }
4914}
4915
4916/// Generates a 'note' diagnostic for an overload candidate. We've
4917/// already generated a primary error at the call site.
4918///
4919/// It really does need to be a single diagnostic with its caret
4920/// pointed at the candidate declaration. Yes, this creates some
4921/// major challenges of technical writing. Yes, this makes pointing
4922/// out problems with specific arguments quite awkward. It's still
4923/// better than generating twenty screens of text for every failed
4924/// overload.
4925///
4926/// It would be great to be able to express per-candidate problems
4927/// more richly for those diagnostic clients that cared, but we'd
4928/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00004929void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4930 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00004931 FunctionDecl *Fn = Cand->Function;
4932
John McCall81201622010-01-08 04:41:39 +00004933 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00004934 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00004935 std::string FnDesc;
4936 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00004937
4938 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00004939 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00004940 return;
John McCall81201622010-01-08 04:41:39 +00004941 }
4942
John McCall220ccbf2010-01-13 00:25:19 +00004943 // We don't really have anything else to say about viable candidates.
4944 if (Cand->Viable) {
4945 S.NoteOverloadCandidate(Fn);
4946 return;
4947 }
John McCall1d318332010-01-12 00:44:57 +00004948
John McCalladbb8f82010-01-13 09:16:55 +00004949 switch (Cand->FailureKind) {
4950 case ovl_fail_too_many_arguments:
4951 case ovl_fail_too_few_arguments:
4952 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00004953
John McCalladbb8f82010-01-13 09:16:55 +00004954 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00004955 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
4956
John McCall717e8912010-01-23 05:17:32 +00004957 case ovl_fail_trivial_conversion:
4958 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00004959 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00004960 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00004961
John McCallb1bdc622010-02-25 01:37:24 +00004962 case ovl_fail_bad_conversion: {
4963 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
4964 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00004965 if (Cand->Conversions[I].isBad())
4966 return DiagnoseBadConversion(S, Cand, I);
4967
4968 // FIXME: this currently happens when we're called from SemaInit
4969 // when user-conversion overload fails. Figure out how to handle
4970 // those conditions and diagnose them well.
4971 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00004972 }
John McCallb1bdc622010-02-25 01:37:24 +00004973 }
John McCalla1d7d622010-01-08 00:58:21 +00004974}
4975
4976void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4977 // Desugar the type of the surrogate down to a function type,
4978 // retaining as many typedefs as possible while still showing
4979 // the function type (and, therefore, its parameter types).
4980 QualType FnType = Cand->Surrogate->getConversionType();
4981 bool isLValueReference = false;
4982 bool isRValueReference = false;
4983 bool isPointer = false;
4984 if (const LValueReferenceType *FnTypeRef =
4985 FnType->getAs<LValueReferenceType>()) {
4986 FnType = FnTypeRef->getPointeeType();
4987 isLValueReference = true;
4988 } else if (const RValueReferenceType *FnTypeRef =
4989 FnType->getAs<RValueReferenceType>()) {
4990 FnType = FnTypeRef->getPointeeType();
4991 isRValueReference = true;
4992 }
4993 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4994 FnType = FnTypePtr->getPointeeType();
4995 isPointer = true;
4996 }
4997 // Desugar down to a function type.
4998 FnType = QualType(FnType->getAs<FunctionType>(), 0);
4999 // Reconstruct the pointer/reference as appropriate.
5000 if (isPointer) FnType = S.Context.getPointerType(FnType);
5001 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5002 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5003
5004 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5005 << FnType;
5006}
5007
5008void NoteBuiltinOperatorCandidate(Sema &S,
5009 const char *Opc,
5010 SourceLocation OpLoc,
5011 OverloadCandidate *Cand) {
5012 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5013 std::string TypeStr("operator");
5014 TypeStr += Opc;
5015 TypeStr += "(";
5016 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5017 if (Cand->Conversions.size() == 1) {
5018 TypeStr += ")";
5019 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5020 } else {
5021 TypeStr += ", ";
5022 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5023 TypeStr += ")";
5024 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5025 }
5026}
5027
5028void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5029 OverloadCandidate *Cand) {
5030 unsigned NoOperands = Cand->Conversions.size();
5031 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5032 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00005033 if (ICS.isBad()) break; // all meaningless after first invalid
5034 if (!ICS.isAmbiguous()) continue;
5035
5036 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005037 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00005038 }
5039}
5040
John McCall1b77e732010-01-15 23:32:50 +00005041SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5042 if (Cand->Function)
5043 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00005044 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00005045 return Cand->Surrogate->getLocation();
5046 return SourceLocation();
5047}
5048
John McCallbf65c0b2010-01-12 00:48:53 +00005049struct CompareOverloadCandidatesForDisplay {
5050 Sema &S;
5051 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00005052
5053 bool operator()(const OverloadCandidate *L,
5054 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00005055 // Fast-path this check.
5056 if (L == R) return false;
5057
John McCall81201622010-01-08 04:41:39 +00005058 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00005059 if (L->Viable) {
5060 if (!R->Viable) return true;
5061
5062 // TODO: introduce a tri-valued comparison for overload
5063 // candidates. Would be more worthwhile if we had a sort
5064 // that could exploit it.
John McCall5769d612010-02-08 23:07:23 +00005065 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5066 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00005067 } else if (R->Viable)
5068 return false;
John McCall81201622010-01-08 04:41:39 +00005069
John McCall1b77e732010-01-15 23:32:50 +00005070 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00005071
John McCall1b77e732010-01-15 23:32:50 +00005072 // Criteria by which we can sort non-viable candidates:
5073 if (!L->Viable) {
5074 // 1. Arity mismatches come after other candidates.
5075 if (L->FailureKind == ovl_fail_too_many_arguments ||
5076 L->FailureKind == ovl_fail_too_few_arguments)
5077 return false;
5078 if (R->FailureKind == ovl_fail_too_many_arguments ||
5079 R->FailureKind == ovl_fail_too_few_arguments)
5080 return true;
John McCall81201622010-01-08 04:41:39 +00005081
John McCall717e8912010-01-23 05:17:32 +00005082 // 2. Bad conversions come first and are ordered by the number
5083 // of bad conversions and quality of good conversions.
5084 if (L->FailureKind == ovl_fail_bad_conversion) {
5085 if (R->FailureKind != ovl_fail_bad_conversion)
5086 return true;
5087
5088 // If there's any ordering between the defined conversions...
5089 // FIXME: this might not be transitive.
5090 assert(L->Conversions.size() == R->Conversions.size());
5091
5092 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00005093 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5094 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall717e8912010-01-23 05:17:32 +00005095 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5096 R->Conversions[I])) {
5097 case ImplicitConversionSequence::Better:
5098 leftBetter++;
5099 break;
5100
5101 case ImplicitConversionSequence::Worse:
5102 leftBetter--;
5103 break;
5104
5105 case ImplicitConversionSequence::Indistinguishable:
5106 break;
5107 }
5108 }
5109 if (leftBetter > 0) return true;
5110 if (leftBetter < 0) return false;
5111
5112 } else if (R->FailureKind == ovl_fail_bad_conversion)
5113 return false;
5114
John McCall1b77e732010-01-15 23:32:50 +00005115 // TODO: others?
5116 }
5117
5118 // Sort everything else by location.
5119 SourceLocation LLoc = GetLocationForCandidate(L);
5120 SourceLocation RLoc = GetLocationForCandidate(R);
5121
5122 // Put candidates without locations (e.g. builtins) at the end.
5123 if (LLoc.isInvalid()) return false;
5124 if (RLoc.isInvalid()) return true;
5125
5126 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00005127 }
5128};
5129
John McCall717e8912010-01-23 05:17:32 +00005130/// CompleteNonViableCandidate - Normally, overload resolution only
5131/// computes up to the first
5132void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5133 Expr **Args, unsigned NumArgs) {
5134 assert(!Cand->Viable);
5135
5136 // Don't do anything on failures other than bad conversion.
5137 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5138
5139 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00005140 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00005141 unsigned ConvCount = Cand->Conversions.size();
5142 while (true) {
5143 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5144 ConvIdx++;
5145 if (Cand->Conversions[ConvIdx - 1].isBad())
5146 break;
5147 }
5148
5149 if (ConvIdx == ConvCount)
5150 return;
5151
John McCallb1bdc622010-02-25 01:37:24 +00005152 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5153 "remaining conversion is initialized?");
5154
John McCall717e8912010-01-23 05:17:32 +00005155 // FIXME: these should probably be preserved from the overload
5156 // operation somehow.
5157 bool SuppressUserConversions = false;
5158 bool ForceRValue = false;
5159
5160 const FunctionProtoType* Proto;
5161 unsigned ArgIdx = ConvIdx;
5162
5163 if (Cand->IsSurrogate) {
5164 QualType ConvType
5165 = Cand->Surrogate->getConversionType().getNonReferenceType();
5166 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5167 ConvType = ConvPtrType->getPointeeType();
5168 Proto = ConvType->getAs<FunctionProtoType>();
5169 ArgIdx--;
5170 } else if (Cand->Function) {
5171 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5172 if (isa<CXXMethodDecl>(Cand->Function) &&
5173 !isa<CXXConstructorDecl>(Cand->Function))
5174 ArgIdx--;
5175 } else {
5176 // Builtin binary operator with a bad first conversion.
5177 assert(ConvCount <= 3);
5178 for (; ConvIdx != ConvCount; ++ConvIdx)
5179 Cand->Conversions[ConvIdx]
5180 = S.TryCopyInitialization(Args[ConvIdx],
5181 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5182 SuppressUserConversions, ForceRValue,
5183 /*InOverloadResolution*/ true);
5184 return;
5185 }
5186
5187 // Fill in the rest of the conversions.
5188 unsigned NumArgsInProto = Proto->getNumArgs();
5189 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5190 if (ArgIdx < NumArgsInProto)
5191 Cand->Conversions[ConvIdx]
5192 = S.TryCopyInitialization(Args[ArgIdx], Proto->getArgType(ArgIdx),
5193 SuppressUserConversions, ForceRValue,
5194 /*InOverloadResolution=*/true);
5195 else
5196 Cand->Conversions[ConvIdx].setEllipsis();
5197 }
5198}
5199
John McCalla1d7d622010-01-08 00:58:21 +00005200} // end anonymous namespace
5201
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005202/// PrintOverloadCandidates - When overload resolution fails, prints
5203/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00005204/// set.
Mike Stump1eb44332009-09-09 15:08:12 +00005205void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005206Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall81201622010-01-08 04:41:39 +00005207 OverloadCandidateDisplayKind OCD,
John McCallcbce6062010-01-12 07:18:19 +00005208 Expr **Args, unsigned NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005209 const char *Opc,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00005210 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00005211 // Sort the candidates by viability and position. Sorting directly would
5212 // be prohibitive, so we make a set of pointers and sort those.
5213 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5214 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5215 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5216 LastCand = CandidateSet.end();
John McCall717e8912010-01-23 05:17:32 +00005217 Cand != LastCand; ++Cand) {
5218 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00005219 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00005220 else if (OCD == OCD_AllCandidates) {
5221 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
5222 Cands.push_back(Cand);
5223 }
5224 }
5225
John McCallbf65c0b2010-01-12 00:48:53 +00005226 std::sort(Cands.begin(), Cands.end(),
5227 CompareOverloadCandidatesForDisplay(*this));
John McCall81201622010-01-08 04:41:39 +00005228
John McCall1d318332010-01-12 00:44:57 +00005229 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00005230
John McCall81201622010-01-08 04:41:39 +00005231 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
5232 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5233 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00005234
John McCalla1d7d622010-01-08 00:58:21 +00005235 if (Cand->Function)
John McCall220ccbf2010-01-13 00:25:19 +00005236 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00005237 else if (Cand->IsSurrogate)
5238 NoteSurrogateCandidate(*this, Cand);
5239
5240 // This a builtin candidate. We do not, in general, want to list
5241 // every possible builtin candidate.
John McCall1d318332010-01-12 00:44:57 +00005242 else if (Cand->Viable) {
5243 // Generally we only see ambiguities including viable builtin
5244 // operators if overload resolution got screwed up by an
5245 // ambiguous user-defined conversion.
5246 //
5247 // FIXME: It's quite possible for different conversions to see
5248 // different ambiguities, though.
5249 if (!ReportedAmbiguousConversions) {
5250 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5251 ReportedAmbiguousConversions = true;
5252 }
John McCalla1d7d622010-01-08 00:58:21 +00005253
John McCall1d318332010-01-12 00:44:57 +00005254 // If this is a viable builtin, print it.
John McCalla1d7d622010-01-08 00:58:21 +00005255 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005256 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005257 }
5258}
5259
John McCall9aa472c2010-03-19 07:35:19 +00005260static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCallc373d482010-01-27 01:50:18 +00005261 if (isa<UnresolvedLookupExpr>(E))
John McCall9aa472c2010-03-19 07:35:19 +00005262 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00005263
John McCall9aa472c2010-03-19 07:35:19 +00005264 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00005265}
5266
Douglas Gregor904eed32008-11-10 20:40:00 +00005267/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5268/// an overloaded function (C++ [over.over]), where @p From is an
5269/// expression with overloaded function type and @p ToType is the type
5270/// we're trying to resolve to. For example:
5271///
5272/// @code
5273/// int f(double);
5274/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00005275///
Douglas Gregor904eed32008-11-10 20:40:00 +00005276/// int (*pfd)(double) = f; // selects f(double)
5277/// @endcode
5278///
5279/// This routine returns the resulting FunctionDecl if it could be
5280/// resolved, and NULL otherwise. When @p Complain is true, this
5281/// routine will emit diagnostics if there is an error.
5282FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00005283Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall6bb80172010-03-30 21:47:33 +00005284 bool Complain,
5285 DeclAccessPair &FoundResult) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005286 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00005287 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00005288 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00005289 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00005290 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00005291 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00005292 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00005293 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00005294 FunctionType = MemTypePtr->getPointeeType();
5295 IsMember = true;
5296 }
Douglas Gregor904eed32008-11-10 20:40:00 +00005297
5298 // We only look at pointers or references to functions.
Douglas Gregor72e771f2009-07-09 17:16:51 +00005299 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor83314aa2009-07-08 20:55:45 +00005300 if (!FunctionType->isFunctionType())
Douglas Gregor904eed32008-11-10 20:40:00 +00005301 return 0;
5302
5303 // Find the actual overloaded function declaration.
John McCall7bb12da2010-02-02 06:20:04 +00005304 if (From->getType() != Context.OverloadTy)
5305 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005306
Douglas Gregor904eed32008-11-10 20:40:00 +00005307 // C++ [over.over]p1:
5308 // [...] [Note: any redundant set of parentheses surrounding the
5309 // overloaded function name is ignored (5.1). ]
Douglas Gregor904eed32008-11-10 20:40:00 +00005310 // C++ [over.over]p1:
5311 // [...] The overloaded function name can be preceded by the &
5312 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00005313 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5314 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5315 if (OvlExpr->hasExplicitTemplateArgs()) {
5316 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5317 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregor904eed32008-11-10 20:40:00 +00005318 }
5319
Douglas Gregor904eed32008-11-10 20:40:00 +00005320 // Look through all of the overloaded functions, searching for one
5321 // whose type matches exactly.
John McCall9aa472c2010-03-19 07:35:19 +00005322 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb7a09262010-04-01 18:32:35 +00005323 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5324
Douglas Gregor00aeb522009-07-08 23:33:52 +00005325 bool FoundNonTemplateFunction = false;
John McCall7bb12da2010-02-02 06:20:04 +00005326 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5327 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00005328 // Look through any using declarations to find the underlying function.
5329 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5330
Douglas Gregor904eed32008-11-10 20:40:00 +00005331 // C++ [over.over]p3:
5332 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00005333 // targets of type "pointer-to-function" or "reference-to-function."
5334 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00005335 // type "pointer-to-member-function."
5336 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00005337
Mike Stump1eb44332009-09-09 15:08:12 +00005338 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00005339 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00005340 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00005341 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00005342 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00005343 // static when converting to member pointer.
5344 if (Method->isStatic() == IsMember)
5345 continue;
5346 } else if (IsMember)
5347 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00005348
Douglas Gregor00aeb522009-07-08 23:33:52 +00005349 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005350 // If the name is a function template, template argument deduction is
5351 // done (14.8.2.2), and if the argument deduction succeeds, the
5352 // resulting template argument list is used to generate a single
5353 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00005354 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005355 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00005356 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00005357 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor83314aa2009-07-08 20:55:45 +00005358 if (TemplateDeductionResult Result
John McCall7bb12da2010-02-02 06:20:04 +00005359 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00005360 FunctionType, Specialization, Info)) {
5361 // FIXME: make a note of the failed deduction for diagnostics.
5362 (void)Result;
5363 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005364 // FIXME: If the match isn't exact, shouldn't we just drop this as
5365 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00005366 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00005367 == Context.getCanonicalType(Specialization->getType()));
John McCall9aa472c2010-03-19 07:35:19 +00005368 Matches.push_back(std::make_pair(I.getPair(),
5369 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor83314aa2009-07-08 20:55:45 +00005370 }
John McCallba135432009-11-21 08:51:07 +00005371
5372 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00005373 }
Mike Stump1eb44332009-09-09 15:08:12 +00005374
Chandler Carruthbd647292009-12-29 06:17:27 +00005375 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00005376 // Skip non-static functions when converting to pointer, and static
5377 // when converting to member pointer.
5378 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00005379 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005380
5381 // If we have explicit template arguments, skip non-templates.
John McCall7bb12da2010-02-02 06:20:04 +00005382 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005383 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00005384 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00005385 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00005386
Chandler Carruthbd647292009-12-29 06:17:27 +00005387 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00005388 QualType ResultTy;
5389 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5390 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5391 ResultTy)) {
John McCall9aa472c2010-03-19 07:35:19 +00005392 Matches.push_back(std::make_pair(I.getPair(),
5393 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00005394 FoundNonTemplateFunction = true;
5395 }
Mike Stump1eb44332009-09-09 15:08:12 +00005396 }
Douglas Gregor904eed32008-11-10 20:40:00 +00005397 }
5398
Douglas Gregor00aeb522009-07-08 23:33:52 +00005399 // If there were 0 or 1 matches, we're done.
5400 if (Matches.empty())
5401 return 0;
Sebastian Redl07ab2022009-10-17 21:12:09 +00005402 else if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00005403 FunctionDecl *Result = Matches[0].second;
John McCall6bb80172010-03-30 21:47:33 +00005404 FoundResult = Matches[0].first;
Sebastian Redl07ab2022009-10-17 21:12:09 +00005405 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCallc373d482010-01-27 01:50:18 +00005406 if (Complain)
John McCall6bb80172010-03-30 21:47:33 +00005407 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redl07ab2022009-10-17 21:12:09 +00005408 return Result;
5409 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00005410
5411 // C++ [over.over]p4:
5412 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00005413 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005414 // [...] and any given function template specialization F1 is
5415 // eliminated if the set contains a second function template
5416 // specialization whose function template is more specialized
5417 // than the function template of F1 according to the partial
5418 // ordering rules of 14.5.5.2.
5419
5420 // The algorithm specified above is quadratic. We instead use a
5421 // two-pass algorithm (similar to the one used to identify the
5422 // best viable function in an overload set) that identifies the
5423 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00005424
5425 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5426 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5427 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCallc373d482010-01-27 01:50:18 +00005428
5429 UnresolvedSetIterator Result =
John McCall9aa472c2010-03-19 07:35:19 +00005430 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00005431 TPOC_Other, From->getLocStart(),
5432 PDiag(),
5433 PDiag(diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00005434 << Matches[0].second->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00005435 PDiag(diag::note_ovl_candidate)
5436 << (unsigned) oc_function_template);
John McCall9aa472c2010-03-19 07:35:19 +00005437 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCallc373d482010-01-27 01:50:18 +00005438 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall6bb80172010-03-30 21:47:33 +00005439 FoundResult = Matches[Result - MatchesCopy.begin()].first;
5440 if (Complain)
5441 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCallc373d482010-01-27 01:50:18 +00005442 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00005443 }
Mike Stump1eb44332009-09-09 15:08:12 +00005444
Douglas Gregor312a2022009-09-26 03:56:17 +00005445 // [...] any function template specializations in the set are
5446 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00005447 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCall9aa472c2010-03-19 07:35:19 +00005448 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCallc373d482010-01-27 01:50:18 +00005449 ++I;
5450 else {
John McCall9aa472c2010-03-19 07:35:19 +00005451 Matches[I] = Matches[--N];
5452 Matches.set_size(N);
John McCallc373d482010-01-27 01:50:18 +00005453 }
5454 }
Douglas Gregor312a2022009-09-26 03:56:17 +00005455
Mike Stump1eb44332009-09-09 15:08:12 +00005456 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00005457 // selected function.
John McCallc373d482010-01-27 01:50:18 +00005458 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00005459 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall6bb80172010-03-30 21:47:33 +00005460 FoundResult = Matches[0].first;
John McCallc373d482010-01-27 01:50:18 +00005461 if (Complain)
John McCall9aa472c2010-03-19 07:35:19 +00005462 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
5463 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redl07ab2022009-10-17 21:12:09 +00005464 }
Mike Stump1eb44332009-09-09 15:08:12 +00005465
Douglas Gregor00aeb522009-07-08 23:33:52 +00005466 // FIXME: We should probably return the same thing that BestViableFunction
5467 // returns (even if we issue the diagnostics here).
5468 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00005469 << Matches[0].second->getDeclName();
5470 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5471 NoteOverloadCandidate(Matches[I].second);
Douglas Gregor904eed32008-11-10 20:40:00 +00005472 return 0;
5473}
5474
Douglas Gregor4b52e252009-12-21 23:17:24 +00005475/// \brief Given an expression that refers to an overloaded function, try to
5476/// resolve that overloaded function expression down to a single function.
5477///
5478/// This routine can only resolve template-ids that refer to a single function
5479/// template, where that template-id refers to a single template whose template
5480/// arguments are either provided by the template-id or have defaults,
5481/// as described in C++0x [temp.arg.explicit]p3.
5482FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5483 // C++ [over.over]p1:
5484 // [...] [Note: any redundant set of parentheses surrounding the
5485 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00005486 // C++ [over.over]p1:
5487 // [...] The overloaded function name can be preceded by the &
5488 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00005489
5490 if (From->getType() != Context.OverloadTy)
5491 return 0;
5492
5493 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor4b52e252009-12-21 23:17:24 +00005494
5495 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00005496 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00005497 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00005498
5499 TemplateArgumentListInfo ExplicitTemplateArgs;
5500 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor4b52e252009-12-21 23:17:24 +00005501
5502 // Look through all of the overloaded functions, searching for one
5503 // whose type matches exactly.
5504 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00005505 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5506 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00005507 // C++0x [temp.arg.explicit]p3:
5508 // [...] In contexts where deduction is done and fails, or in contexts
5509 // where deduction is not done, if a template argument list is
5510 // specified and it, along with any default template arguments,
5511 // identifies a single function template specialization, then the
5512 // template-id is an lvalue for the function template specialization.
5513 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5514
5515 // C++ [over.over]p2:
5516 // If the name is a function template, template argument deduction is
5517 // done (14.8.2.2), and if the argument deduction succeeds, the
5518 // resulting template argument list is used to generate a single
5519 // function template specialization, which is added to the set of
5520 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00005521 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00005522 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00005523 if (TemplateDeductionResult Result
5524 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5525 Specialization, Info)) {
5526 // FIXME: make a note of the failed deduction for diagnostics.
5527 (void)Result;
5528 continue;
5529 }
5530
5531 // Multiple matches; we can't resolve to a single declaration.
5532 if (Matched)
5533 return 0;
5534
5535 Matched = Specialization;
5536 }
5537
5538 return Matched;
5539}
5540
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005541/// \brief Add a single candidate to the overload set.
5542static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00005543 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00005544 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005545 Expr **Args, unsigned NumArgs,
5546 OverloadCandidateSet &CandidateSet,
5547 bool PartialOverloading) {
John McCall9aa472c2010-03-19 07:35:19 +00005548 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00005549 if (isa<UsingShadowDecl>(Callee))
5550 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5551
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005552 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00005553 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall9aa472c2010-03-19 07:35:19 +00005554 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
John McCall86820f52010-01-26 01:37:31 +00005555 false, false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005556 return;
John McCallba135432009-11-21 08:51:07 +00005557 }
5558
5559 if (FunctionTemplateDecl *FuncTemplate
5560 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00005561 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
5562 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00005563 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00005564 return;
5565 }
5566
5567 assert(false && "unhandled case in overloaded call candidate");
5568
5569 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005570}
5571
5572/// \brief Add the overload candidates named by callee and/or found by argument
5573/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00005574void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005575 Expr **Args, unsigned NumArgs,
5576 OverloadCandidateSet &CandidateSet,
5577 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00005578
5579#ifndef NDEBUG
5580 // Verify that ArgumentDependentLookup is consistent with the rules
5581 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005582 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005583 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5584 // and let Y be the lookup set produced by argument dependent
5585 // lookup (defined as follows). If X contains
5586 //
5587 // -- a declaration of a class member, or
5588 //
5589 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00005590 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005591 //
5592 // -- a declaration that is neither a function or a function
5593 // template
5594 //
5595 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00005596
John McCall3b4294e2009-12-16 12:17:52 +00005597 if (ULE->requiresADL()) {
5598 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5599 E = ULE->decls_end(); I != E; ++I) {
5600 assert(!(*I)->getDeclContext()->isRecord());
5601 assert(isa<UsingShadowDecl>(*I) ||
5602 !(*I)->getDeclContext()->isFunctionOrMethod());
5603 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00005604 }
5605 }
5606#endif
5607
John McCall3b4294e2009-12-16 12:17:52 +00005608 // It would be nice to avoid this copy.
5609 TemplateArgumentListInfo TABuffer;
5610 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5611 if (ULE->hasExplicitTemplateArgs()) {
5612 ULE->copyTemplateArgumentsInto(TABuffer);
5613 ExplicitTemplateArgs = &TABuffer;
5614 }
5615
5616 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5617 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00005618 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00005619 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005620 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00005621
John McCall3b4294e2009-12-16 12:17:52 +00005622 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00005623 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5624 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005625 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005626 CandidateSet,
5627 PartialOverloading);
5628}
John McCall578b69b2009-12-16 08:11:27 +00005629
John McCall3b4294e2009-12-16 12:17:52 +00005630static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5631 Expr **Args, unsigned NumArgs) {
5632 Fn->Destroy(SemaRef.Context);
5633 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5634 Args[Arg]->Destroy(SemaRef.Context);
5635 return SemaRef.ExprError();
5636}
5637
John McCall578b69b2009-12-16 08:11:27 +00005638/// Attempts to recover from a call where no functions were found.
5639///
5640/// Returns true if new candidates were found.
John McCall3b4294e2009-12-16 12:17:52 +00005641static Sema::OwningExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00005642BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00005643 UnresolvedLookupExpr *ULE,
5644 SourceLocation LParenLoc,
5645 Expr **Args, unsigned NumArgs,
5646 SourceLocation *CommaLocs,
5647 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00005648
5649 CXXScopeSpec SS;
5650 if (ULE->getQualifier()) {
5651 SS.setScopeRep(ULE->getQualifier());
5652 SS.setRange(ULE->getQualifierRange());
5653 }
5654
John McCall3b4294e2009-12-16 12:17:52 +00005655 TemplateArgumentListInfo TABuffer;
5656 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5657 if (ULE->hasExplicitTemplateArgs()) {
5658 ULE->copyTemplateArgumentsInto(TABuffer);
5659 ExplicitTemplateArgs = &TABuffer;
5660 }
5661
John McCall578b69b2009-12-16 08:11:27 +00005662 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5663 Sema::LookupOrdinaryName);
Douglas Gregor1aae80b2010-04-14 20:27:54 +00005664 if (SemaRef.DiagnoseEmptyLookup(S, SS, R))
John McCall3b4294e2009-12-16 12:17:52 +00005665 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCall578b69b2009-12-16 08:11:27 +00005666
John McCall3b4294e2009-12-16 12:17:52 +00005667 assert(!R.empty() && "lookup results empty despite recovery");
5668
5669 // Build an implicit member call if appropriate. Just drop the
5670 // casts and such from the call, we don't really care.
5671 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5672 if ((*R.begin())->isCXXClassMember())
5673 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5674 else if (ExplicitTemplateArgs)
5675 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5676 else
5677 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5678
5679 if (NewFn.isInvalid())
5680 return Destroy(SemaRef, Fn, Args, NumArgs);
5681
5682 Fn->Destroy(SemaRef.Context);
5683
5684 // This shouldn't cause an infinite loop because we're giving it
5685 // an expression with non-empty lookup results, which should never
5686 // end up here.
5687 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5688 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5689 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00005690}
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005691
Douglas Gregorf6b89692008-11-26 05:54:23 +00005692/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00005693/// (which eventually refers to the declaration Func) and the call
5694/// arguments Args/NumArgs, attempt to resolve the function call down
5695/// to a specific function. If overload resolution succeeds, returns
5696/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00005697/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00005698/// arguments and Fn, and returns NULL.
John McCall3b4294e2009-12-16 12:17:52 +00005699Sema::OwningExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00005700Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00005701 SourceLocation LParenLoc,
5702 Expr **Args, unsigned NumArgs,
5703 SourceLocation *CommaLocs,
5704 SourceLocation RParenLoc) {
5705#ifndef NDEBUG
5706 if (ULE->requiresADL()) {
5707 // To do ADL, we must have found an unqualified name.
5708 assert(!ULE->getQualifier() && "qualified name with ADL");
5709
5710 // We don't perform ADL for implicit declarations of builtins.
5711 // Verify that this was correctly set up.
5712 FunctionDecl *F;
5713 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5714 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5715 F->getBuiltinID() && F->isImplicit())
5716 assert(0 && "performing ADL for builtin");
5717
5718 // We don't perform ADL in C.
5719 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5720 }
5721#endif
5722
John McCall5769d612010-02-08 23:07:23 +00005723 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00005724
John McCall3b4294e2009-12-16 12:17:52 +00005725 // Add the functions denoted by the callee to the set of candidate
5726 // functions, including those from argument-dependent lookup.
5727 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00005728
5729 // If we found nothing, try to recover.
5730 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5731 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00005732 if (CandidateSet.empty())
Douglas Gregor1aae80b2010-04-14 20:27:54 +00005733 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00005734 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00005735
Douglas Gregorf6b89692008-11-26 05:54:23 +00005736 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005737 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00005738 case OR_Success: {
5739 FunctionDecl *FDecl = Best->Function;
John McCall9aa472c2010-03-19 07:35:19 +00005740 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall6bb80172010-03-30 21:47:33 +00005741 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall3b4294e2009-12-16 12:17:52 +00005742 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5743 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00005744
5745 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00005746 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00005747 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00005748 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005749 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00005750 break;
5751
5752 case OR_Ambiguous:
5753 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00005754 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005755 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00005756 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005757
5758 case OR_Deleted:
5759 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5760 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00005761 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005762 << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005763 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005764 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00005765 }
5766
5767 // Overload resolution failed. Destroy all of the subexpressions and
5768 // return NULL.
5769 Fn->Destroy(Context);
5770 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5771 Args[Arg]->Destroy(Context);
John McCall3b4294e2009-12-16 12:17:52 +00005772 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00005773}
5774
John McCall6e266892010-01-26 03:27:55 +00005775static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00005776 return Functions.size() > 1 ||
5777 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5778}
5779
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005780/// \brief Create a unary operation that may resolve to an overloaded
5781/// operator.
5782///
5783/// \param OpLoc The location of the operator itself (e.g., '*').
5784///
5785/// \param OpcIn The UnaryOperator::Opcode that describes this
5786/// operator.
5787///
5788/// \param Functions The set of non-member functions that will be
5789/// considered by overload resolution. The caller needs to build this
5790/// set based on the context using, e.g.,
5791/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5792/// set should not contain any member functions; those will be added
5793/// by CreateOverloadedUnaryOp().
5794///
5795/// \param input The input argument.
John McCall6e266892010-01-26 03:27:55 +00005796Sema::OwningExprResult
5797Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
5798 const UnresolvedSetImpl &Fns,
5799 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005800 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5801 Expr *Input = (Expr *)input.get();
5802
5803 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5804 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5805 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5806
5807 Expr *Args[2] = { Input, 0 };
5808 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00005809
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005810 // For post-increment and post-decrement, add the implicit '0' as
5811 // the second argument, so that we know this is a post-increment or
5812 // post-decrement.
5813 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5814 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00005815 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005816 SourceLocation());
5817 NumArgs = 2;
5818 }
5819
5820 if (Input->isTypeDependent()) {
John McCallc373d482010-01-27 01:50:18 +00005821 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00005822 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00005823 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00005824 0, SourceRange(), OpName, OpLoc,
John McCall6e266892010-01-26 03:27:55 +00005825 /*ADL*/ true, IsOverloaded(Fns));
5826 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump1eb44332009-09-09 15:08:12 +00005827
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005828 input.release();
5829 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5830 &Args[0], NumArgs,
5831 Context.DependentTy,
5832 OpLoc));
5833 }
5834
5835 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00005836 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005837
5838 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00005839 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005840
5841 // Add operator candidates that are member functions.
5842 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5843
John McCall6e266892010-01-26 03:27:55 +00005844 // Add candidates from ADL.
5845 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00005846 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00005847 /*ExplicitTemplateArgs*/ 0,
5848 CandidateSet);
5849
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005850 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00005851 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005852
5853 // Perform overload resolution.
5854 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005855 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005856 case OR_Success: {
5857 // We found a built-in operator or an overloaded operator.
5858 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00005859
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005860 if (FnDecl) {
5861 // We matched an overloaded operator. Build a call to that
5862 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00005863
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005864 // Convert the arguments.
5865 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00005866 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00005867
John McCall6bb80172010-03-30 21:47:33 +00005868 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
5869 Best->FoundDecl, Method))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005870 return ExprError();
5871 } else {
5872 // Convert the arguments.
Douglas Gregore1a5c172009-12-23 17:40:29 +00005873 OwningExprResult InputInit
5874 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005875 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00005876 SourceLocation(),
5877 move(input));
5878 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005879 return ExprError();
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005880
Douglas Gregore1a5c172009-12-23 17:40:29 +00005881 input = move(InputInit);
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005882 Input = (Expr *)input.get();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005883 }
5884
5885 // Determine the result type
Anders Carlsson26a2a072009-10-13 21:19:37 +00005886 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00005887
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005888 // Build the actual expression node.
5889 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5890 SourceLocation());
5891 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00005892
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005893 input.release();
Eli Friedman4c3b8962009-11-18 03:58:17 +00005894 Args[0] = Input;
Anders Carlsson26a2a072009-10-13 21:19:37 +00005895 ExprOwningPtr<CallExpr> TheCall(this,
5896 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman4c3b8962009-11-18 03:58:17 +00005897 Args, NumArgs, ResultTy, OpLoc));
Anders Carlsson26a2a072009-10-13 21:19:37 +00005898
5899 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5900 FnDecl))
5901 return ExprError();
5902
5903 return MaybeBindToTemporary(TheCall.release());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005904 } else {
5905 // We matched a built-in operator. Convert the arguments, then
5906 // break out so that we will build the appropriate built-in
5907 // operator node.
5908 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005909 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005910 return ExprError();
5911
5912 break;
5913 }
5914 }
5915
5916 case OR_No_Viable_Function:
5917 // No viable function; fall through to handling this as a
5918 // built-in operator, which will produce an error message for us.
5919 break;
5920
5921 case OR_Ambiguous:
5922 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5923 << UnaryOperator::getOpcodeStr(Opc)
5924 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005925 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005926 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005927 return ExprError();
5928
5929 case OR_Deleted:
5930 Diag(OpLoc, diag::err_ovl_deleted_oper)
5931 << Best->Function->isDeleted()
5932 << UnaryOperator::getOpcodeStr(Opc)
5933 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005934 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005935 return ExprError();
5936 }
5937
5938 // Either we found no viable overloaded operator or we matched a
5939 // built-in operator. In either case, fall through to trying to
5940 // build a built-in operation.
5941 input.release();
5942 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5943}
5944
Douglas Gregor063daf62009-03-13 18:40:31 +00005945/// \brief Create a binary operation that may resolve to an overloaded
5946/// operator.
5947///
5948/// \param OpLoc The location of the operator itself (e.g., '+').
5949///
5950/// \param OpcIn The BinaryOperator::Opcode that describes this
5951/// operator.
5952///
5953/// \param Functions The set of non-member functions that will be
5954/// considered by overload resolution. The caller needs to build this
5955/// set based on the context using, e.g.,
5956/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5957/// set should not contain any member functions; those will be added
5958/// by CreateOverloadedBinOp().
5959///
5960/// \param LHS Left-hand argument.
5961/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00005962Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00005963Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005964 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00005965 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00005966 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00005967 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005968 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00005969
5970 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5971 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5972 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5973
5974 // If either side is type-dependent, create an appropriate dependent
5975 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005976 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00005977 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005978 // If there are no functions to store, just build a dependent
5979 // BinaryOperator or CompoundAssignment.
5980 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5981 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5982 Context.DependentTy, OpLoc));
5983
5984 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5985 Context.DependentTy,
5986 Context.DependentTy,
5987 Context.DependentTy,
5988 OpLoc));
5989 }
John McCall6e266892010-01-26 03:27:55 +00005990
5991 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00005992 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00005993 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00005994 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00005995 0, SourceRange(), OpName, OpLoc,
John McCall6e266892010-01-26 03:27:55 +00005996 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump1eb44332009-09-09 15:08:12 +00005997
John McCall6e266892010-01-26 03:27:55 +00005998 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00005999 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00006000 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00006001 Context.DependentTy,
6002 OpLoc));
6003 }
6004
6005 // If this is the .* operator, which is not overloadable, just
6006 // create a built-in binary operator.
6007 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006008 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006009
Sebastian Redl275c2b42009-11-18 23:10:33 +00006010 // If this is the assignment operator, we only perform overload resolution
6011 // if the left-hand side is a class or enumeration type. This is actually
6012 // a hack. The standard requires that we do overload resolution between the
6013 // various built-in candidates, but as DR507 points out, this can lead to
6014 // problems. So we do it this way, which pretty much follows what GCC does.
6015 // Note that we go the traditional code path for compound assignment forms.
6016 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006017 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006018
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006019 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006020 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006021
6022 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00006023 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00006024
6025 // Add operator candidates that are member functions.
6026 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6027
John McCall6e266892010-01-26 03:27:55 +00006028 // Add candidates from ADL.
6029 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6030 Args, 2,
6031 /*ExplicitTemplateArgs*/ 0,
6032 CandidateSet);
6033
Douglas Gregor063daf62009-03-13 18:40:31 +00006034 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00006035 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00006036
6037 // Perform overload resolution.
6038 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006039 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00006040 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00006041 // We found a built-in operator or an overloaded operator.
6042 FunctionDecl *FnDecl = Best->Function;
6043
6044 if (FnDecl) {
6045 // We matched an overloaded operator. Build a call to that
6046 // operator.
6047
6048 // Convert the arguments.
6049 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00006050 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00006051 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00006052
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006053 OwningExprResult Arg1
6054 = PerformCopyInitialization(
6055 InitializedEntity::InitializeParameter(
6056 FnDecl->getParamDecl(0)),
6057 SourceLocation(),
6058 Owned(Args[1]));
6059 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00006060 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006061
Douglas Gregor5fccd362010-03-03 23:55:11 +00006062 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00006063 Best->FoundDecl, Method))
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006064 return ExprError();
6065
6066 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00006067 } else {
6068 // Convert the arguments.
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006069 OwningExprResult Arg0
6070 = PerformCopyInitialization(
6071 InitializedEntity::InitializeParameter(
6072 FnDecl->getParamDecl(0)),
6073 SourceLocation(),
6074 Owned(Args[0]));
6075 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00006076 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006077
6078 OwningExprResult Arg1
6079 = PerformCopyInitialization(
6080 InitializedEntity::InitializeParameter(
6081 FnDecl->getParamDecl(1)),
6082 SourceLocation(),
6083 Owned(Args[1]));
6084 if (Arg1.isInvalid())
6085 return ExprError();
6086 Args[0] = LHS = Arg0.takeAs<Expr>();
6087 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00006088 }
6089
6090 // Determine the result type
6091 QualType ResultTy
John McCall183700f2009-09-21 23:43:11 +00006092 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor063daf62009-03-13 18:40:31 +00006093 ResultTy = ResultTy.getNonReferenceType();
6094
6095 // Build the actual expression node.
6096 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00006097 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006098 UsualUnaryConversions(FnExpr);
6099
Anders Carlsson15ea3782009-10-13 22:43:21 +00006100 ExprOwningPtr<CXXOperatorCallExpr>
6101 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6102 Args, 2, ResultTy,
6103 OpLoc));
6104
6105 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6106 FnDecl))
6107 return ExprError();
6108
6109 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor063daf62009-03-13 18:40:31 +00006110 } else {
6111 // We matched a built-in operator. Convert the arguments, then
6112 // break out so that we will build the appropriate built-in
6113 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006114 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006115 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006116 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00006117 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00006118 return ExprError();
6119
6120 break;
6121 }
6122 }
6123
Douglas Gregor33074752009-09-30 21:46:01 +00006124 case OR_No_Viable_Function: {
6125 // C++ [over.match.oper]p9:
6126 // If the operator is the operator , [...] and there are no
6127 // viable functions, then the operator is assumed to be the
6128 // built-in operator and interpreted according to clause 5.
6129 if (Opc == BinaryOperator::Comma)
6130 break;
6131
Sebastian Redl8593c782009-05-21 11:50:50 +00006132 // For class as left operand for assignment or compound assigment operator
6133 // do not fall through to handling in built-in, but report that no overloaded
6134 // assignment operator found
Douglas Gregor33074752009-09-30 21:46:01 +00006135 OwningExprResult Result = ExprError();
6136 if (Args[0]->getType()->isRecordType() &&
6137 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00006138 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6139 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006140 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00006141 } else {
6142 // No viable function; try to create a built-in operation, which will
6143 // produce an error. Then, show the non-viable candidates.
6144 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00006145 }
Douglas Gregor33074752009-09-30 21:46:01 +00006146 assert(Result.isInvalid() &&
6147 "C++ binary operator overloading is missing candidates!");
6148 if (Result.isInvalid())
John McCallcbce6062010-01-12 07:18:19 +00006149 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006150 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00006151 return move(Result);
6152 }
Douglas Gregor063daf62009-03-13 18:40:31 +00006153
6154 case OR_Ambiguous:
6155 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6156 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006157 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006158 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006159 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006160 return ExprError();
6161
6162 case OR_Deleted:
6163 Diag(OpLoc, diag::err_ovl_deleted_oper)
6164 << Best->Function->isDeleted()
6165 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006166 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006167 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00006168 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00006169 }
Douglas Gregor063daf62009-03-13 18:40:31 +00006170
Douglas Gregor33074752009-09-30 21:46:01 +00006171 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006172 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006173}
6174
Sebastian Redlf322ed62009-10-29 20:17:01 +00006175Action::OwningExprResult
6176Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6177 SourceLocation RLoc,
6178 ExprArg Base, ExprArg Idx) {
6179 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6180 static_cast<Expr*>(Idx.get()) };
6181 DeclarationName OpName =
6182 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6183
6184 // If either side is type-dependent, create an appropriate dependent
6185 // expression.
6186 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6187
John McCallc373d482010-01-27 01:50:18 +00006188 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006189 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006190 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00006191 0, SourceRange(), OpName, LLoc,
John McCall7453ed42009-11-22 00:44:51 +00006192 /*ADL*/ true, /*Overloaded*/ false);
John McCallf7a1a742009-11-24 19:00:30 +00006193 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00006194
6195 Base.release();
6196 Idx.release();
6197 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6198 Args, 2,
6199 Context.DependentTy,
6200 RLoc));
6201 }
6202
6203 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006204 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00006205
6206 // Subscript can only be overloaded as a member function.
6207
6208 // Add operator candidates that are member functions.
6209 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6210
6211 // Add builtin operator candidates.
6212 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6213
6214 // Perform overload resolution.
6215 OverloadCandidateSet::iterator Best;
6216 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6217 case OR_Success: {
6218 // We found a built-in operator or an overloaded operator.
6219 FunctionDecl *FnDecl = Best->Function;
6220
6221 if (FnDecl) {
6222 // We matched an overloaded operator. Build a call to that
6223 // operator.
6224
John McCall9aa472c2010-03-19 07:35:19 +00006225 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallc373d482010-01-27 01:50:18 +00006226
Sebastian Redlf322ed62009-10-29 20:17:01 +00006227 // Convert the arguments.
6228 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregor5fccd362010-03-03 23:55:11 +00006229 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00006230 Best->FoundDecl, Method))
Sebastian Redlf322ed62009-10-29 20:17:01 +00006231 return ExprError();
6232
Anders Carlsson38f88ab2010-01-29 18:37:50 +00006233 // Convert the arguments.
6234 OwningExprResult InputInit
6235 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6236 FnDecl->getParamDecl(0)),
6237 SourceLocation(),
6238 Owned(Args[1]));
6239 if (InputInit.isInvalid())
6240 return ExprError();
6241
6242 Args[1] = InputInit.takeAs<Expr>();
6243
Sebastian Redlf322ed62009-10-29 20:17:01 +00006244 // Determine the result type
6245 QualType ResultTy
6246 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6247 ResultTy = ResultTy.getNonReferenceType();
6248
6249 // Build the actual expression node.
6250 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6251 LLoc);
6252 UsualUnaryConversions(FnExpr);
6253
6254 Base.release();
6255 Idx.release();
6256 ExprOwningPtr<CXXOperatorCallExpr>
6257 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6258 FnExpr, Args, 2,
6259 ResultTy, RLoc));
6260
6261 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6262 FnDecl))
6263 return ExprError();
6264
6265 return MaybeBindToTemporary(TheCall.release());
6266 } else {
6267 // We matched a built-in operator. Convert the arguments, then
6268 // break out so that we will build the appropriate built-in
6269 // operator node.
6270 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006271 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00006272 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00006273 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00006274 return ExprError();
6275
6276 break;
6277 }
6278 }
6279
6280 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00006281 if (CandidateSet.empty())
6282 Diag(LLoc, diag::err_ovl_no_oper)
6283 << Args[0]->getType() << /*subscript*/ 0
6284 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6285 else
6286 Diag(LLoc, diag::err_ovl_no_viable_subscript)
6287 << Args[0]->getType()
6288 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006289 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall1eb3e102010-01-07 02:04:15 +00006290 "[]", LLoc);
6291 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00006292 }
6293
6294 case OR_Ambiguous:
6295 Diag(LLoc, diag::err_ovl_ambiguous_oper)
6296 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006297 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redlf322ed62009-10-29 20:17:01 +00006298 "[]", LLoc);
6299 return ExprError();
6300
6301 case OR_Deleted:
6302 Diag(LLoc, diag::err_ovl_deleted_oper)
6303 << Best->Function->isDeleted() << "[]"
6304 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006305 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall81201622010-01-08 04:41:39 +00006306 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00006307 return ExprError();
6308 }
6309
6310 // We matched a built-in operator; build it.
6311 Base.release();
6312 Idx.release();
6313 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6314 Owned(Args[1]), RLoc);
6315}
6316
Douglas Gregor88a35142008-12-22 05:46:06 +00006317/// BuildCallToMemberFunction - Build a call to a member
6318/// function. MemExpr is the expression that refers to the member
6319/// function (and includes the object parameter), Args/NumArgs are the
6320/// arguments to the function call (not including the object
6321/// parameter). The caller needs to validate that the member
6322/// expression refers to a member function or an overloaded member
6323/// function.
John McCallaa81e162009-12-01 22:10:20 +00006324Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00006325Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6326 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00006327 unsigned NumArgs, SourceLocation *CommaLocs,
6328 SourceLocation RParenLoc) {
6329 // Dig out the member expression. This holds both the object
6330 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00006331 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6332
John McCall129e2df2009-11-30 22:42:35 +00006333 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00006334 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00006335 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00006336 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00006337 if (isa<MemberExpr>(NakedMemExpr)) {
6338 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00006339 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00006340 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00006341 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00006342 } else {
6343 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00006344 Qualifier = UnresExpr->getQualifier();
6345
John McCall701c89e2009-12-03 04:06:58 +00006346 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00006347
Douglas Gregor88a35142008-12-22 05:46:06 +00006348 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00006349 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00006350
John McCallaa81e162009-12-01 22:10:20 +00006351 // FIXME: avoid copy.
6352 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6353 if (UnresExpr->hasExplicitTemplateArgs()) {
6354 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6355 TemplateArgs = &TemplateArgsBuffer;
6356 }
6357
John McCall129e2df2009-11-30 22:42:35 +00006358 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6359 E = UnresExpr->decls_end(); I != E; ++I) {
6360
John McCall701c89e2009-12-03 04:06:58 +00006361 NamedDecl *Func = *I;
6362 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6363 if (isa<UsingShadowDecl>(Func))
6364 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6365
John McCall129e2df2009-11-30 22:42:35 +00006366 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006367 // If explicit template arguments were provided, we can't call a
6368 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00006369 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006370 continue;
6371
John McCall9aa472c2010-03-19 07:35:19 +00006372 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCall86820f52010-01-26 01:37:31 +00006373 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00006374 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00006375 } else {
John McCall129e2df2009-11-30 22:42:35 +00006376 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00006377 I.getPair(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00006378 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00006379 CandidateSet,
6380 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00006381 }
Douglas Gregordec06662009-08-21 18:42:58 +00006382 }
Mike Stump1eb44332009-09-09 15:08:12 +00006383
John McCall129e2df2009-11-30 22:42:35 +00006384 DeclarationName DeclName = UnresExpr->getMemberName();
6385
Douglas Gregor88a35142008-12-22 05:46:06 +00006386 OverloadCandidateSet::iterator Best;
John McCall129e2df2009-11-30 22:42:35 +00006387 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00006388 case OR_Success:
6389 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00006390 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00006391 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Douglas Gregor88a35142008-12-22 05:46:06 +00006392 break;
6393
6394 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00006395 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00006396 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00006397 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006398 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00006399 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006400 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006401
6402 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00006403 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00006404 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006405 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00006406 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006407 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006408
6409 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00006410 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006411 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00006412 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006413 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006414 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006415 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006416 }
6417
John McCall6bb80172010-03-30 21:47:33 +00006418 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00006419
John McCallaa81e162009-12-01 22:10:20 +00006420 // If overload resolution picked a static member, build a
6421 // non-member call based on that function.
6422 if (Method->isStatic()) {
6423 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6424 Args, NumArgs, RParenLoc);
6425 }
6426
John McCall129e2df2009-11-30 22:42:35 +00006427 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00006428 }
6429
6430 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00006431 ExprOwningPtr<CXXMemberCallExpr>
John McCallaa81e162009-12-01 22:10:20 +00006432 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00006433 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00006434 Method->getResultType().getNonReferenceType(),
6435 RParenLoc));
6436
Anders Carlssoneed3e692009-10-10 00:06:20 +00006437 // Check for a valid return type.
6438 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6439 TheCall.get(), Method))
John McCallaa81e162009-12-01 22:10:20 +00006440 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00006441
Douglas Gregor88a35142008-12-22 05:46:06 +00006442 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00006443 // We only need to do this if there was actually an overload; otherwise
6444 // it was done at lookup.
John McCallaa81e162009-12-01 22:10:20 +00006445 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00006446 if (!Method->isStatic() &&
John McCall6bb80172010-03-30 21:47:33 +00006447 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
6448 FoundDecl, Method))
John McCallaa81e162009-12-01 22:10:20 +00006449 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006450 MemExpr->setBase(ObjectArg);
6451
6452 // Convert the rest of the arguments
Douglas Gregor72564e72009-02-26 23:50:07 +00006453 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00006454 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00006455 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00006456 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006457
Anders Carlssond406bf02009-08-16 01:56:34 +00006458 if (CheckFunctionCall(Method, TheCall.get()))
John McCallaa81e162009-12-01 22:10:20 +00006459 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00006460
John McCallaa81e162009-12-01 22:10:20 +00006461 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor88a35142008-12-22 05:46:06 +00006462}
6463
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006464/// BuildCallToObjectOfClassType - Build a call to an object of class
6465/// type (C++ [over.call.object]), which can end up invoking an
6466/// overloaded function call operator (@c operator()) or performing a
6467/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00006468Sema::ExprResult
6469Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00006470 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006471 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00006472 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006473 SourceLocation RParenLoc) {
6474 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00006475 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006476
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006477 // C++ [over.call.object]p1:
6478 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00006479 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006480 // candidate functions includes at least the function call
6481 // operators of T. The function call operators of T are obtained by
6482 // ordinary lookup of the name operator() in the context of
6483 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00006484 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00006485 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00006486
6487 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006488 PDiag(diag::err_incomplete_object_call)
Douglas Gregor593564b2009-11-15 07:48:03 +00006489 << Object->getSourceRange()))
6490 return true;
6491
John McCalla24dc2e2009-11-17 02:14:36 +00006492 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6493 LookupQualifiedName(R, Record->getDecl());
6494 R.suppressDiagnostics();
6495
Douglas Gregor593564b2009-11-15 07:48:03 +00006496 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00006497 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00006498 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCall86820f52010-01-26 01:37:31 +00006499 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006500 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00006501 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00006502
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006503 // C++ [over.call.object]p2:
6504 // In addition, for each conversion function declared in T of the
6505 // form
6506 //
6507 // operator conversion-type-id () cv-qualifier;
6508 //
6509 // where cv-qualifier is the same cv-qualification as, or a
6510 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00006511 // denotes the type "pointer to function of (P1,...,Pn) returning
6512 // R", or the type "reference to pointer to function of
6513 // (P1,...,Pn) returning R", or the type "reference to function
6514 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006515 // is also considered as a candidate function. Similarly,
6516 // surrogate call functions are added to the set of candidate
6517 // functions for each conversion function declared in an
6518 // accessible base class provided the function is not hidden
6519 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00006520 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00006521 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00006522 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00006523 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00006524 NamedDecl *D = *I;
6525 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6526 if (isa<UsingShadowDecl>(D))
6527 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6528
Douglas Gregor4a27d702009-10-21 06:18:39 +00006529 // Skip over templated conversion functions; they aren't
6530 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00006531 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00006532 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006533
John McCall701c89e2009-12-03 04:06:58 +00006534 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00006535
Douglas Gregor4a27d702009-10-21 06:18:39 +00006536 // Strip the reference type (if any) and then the pointer type (if
6537 // any) to get down to what might be a function type.
6538 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6539 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6540 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006541
Douglas Gregor4a27d702009-10-21 06:18:39 +00006542 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall9aa472c2010-03-19 07:35:19 +00006543 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00006544 Object->getType(), Args, NumArgs,
6545 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006546 }
Mike Stump1eb44332009-09-09 15:08:12 +00006547
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006548 // Perform overload resolution.
6549 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006550 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006551 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006552 // Overload resolution succeeded; we'll build the appropriate call
6553 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006554 break;
6555
6556 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00006557 if (CandidateSet.empty())
6558 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6559 << Object->getType() << /*call*/ 1
6560 << Object->getSourceRange();
6561 else
6562 Diag(Object->getSourceRange().getBegin(),
6563 diag::err_ovl_no_viable_object_call)
6564 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006565 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006566 break;
6567
6568 case OR_Ambiguous:
6569 Diag(Object->getSourceRange().getBegin(),
6570 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00006571 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006572 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006573 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006574
6575 case OR_Deleted:
6576 Diag(Object->getSourceRange().getBegin(),
6577 diag::err_ovl_deleted_object_call)
6578 << Best->Function->isDeleted()
6579 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006580 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006581 break;
Mike Stump1eb44332009-09-09 15:08:12 +00006582 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006583
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006584 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006585 // We had an error; delete all of the subexpressions and return
6586 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00006587 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006588 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00006589 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006590 return true;
6591 }
6592
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006593 if (Best->Function == 0) {
6594 // Since there is no function declaration, this is one of the
6595 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00006596 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006597 = cast<CXXConversionDecl>(
6598 Best->Conversions[0].UserDefined.ConversionFunction);
6599
John McCall9aa472c2010-03-19 07:35:19 +00006600 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall41d89032010-01-28 01:54:34 +00006601
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006602 // We selected one of the surrogate functions that converts the
6603 // object parameter to a function pointer. Perform the conversion
6604 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00006605
6606 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00006607 // and then call it.
John McCall6bb80172010-03-30 21:47:33 +00006608 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
6609 Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00006610
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00006611 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00006612 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregoraa0be172010-04-13 15:50:39 +00006613 CommaLocs, RParenLoc).result();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006614 }
6615
John McCall9aa472c2010-03-19 07:35:19 +00006616 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall41d89032010-01-28 01:54:34 +00006617
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006618 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6619 // that calls this method, using Object for the implicit object
6620 // parameter and passing along the remaining arguments.
6621 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00006622 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006623
6624 unsigned NumArgsInProto = Proto->getNumArgs();
6625 unsigned NumArgsToCheck = NumArgs;
6626
6627 // Build the full argument list for the method call (the
6628 // implicit object parameter is placed at the beginning of the
6629 // list).
6630 Expr **MethodArgs;
6631 if (NumArgs < NumArgsInProto) {
6632 NumArgsToCheck = NumArgsInProto;
6633 MethodArgs = new Expr*[NumArgsInProto + 1];
6634 } else {
6635 MethodArgs = new Expr*[NumArgs + 1];
6636 }
6637 MethodArgs[0] = Object;
6638 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6639 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00006640
6641 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00006642 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006643 UsualUnaryConversions(NewFn);
6644
6645 // Once we've built TheCall, all of the expressions are properly
6646 // owned.
6647 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00006648 ExprOwningPtr<CXXOperatorCallExpr>
6649 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00006650 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00006651 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006652 delete [] MethodArgs;
6653
Anders Carlsson07d68f12009-10-13 21:49:31 +00006654 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6655 Method))
6656 return true;
6657
Douglas Gregor518fda12009-01-13 05:10:00 +00006658 // We may have default arguments. If so, we need to allocate more
6659 // slots in the call for them.
6660 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00006661 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00006662 else if (NumArgs > NumArgsInProto)
6663 NumArgsToCheck = NumArgsInProto;
6664
Chris Lattner312531a2009-04-12 08:11:20 +00006665 bool IsError = false;
6666
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006667 // Initialize the implicit object parameter.
Douglas Gregor5fccd362010-03-03 23:55:11 +00006668 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00006669 Best->FoundDecl, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006670 TheCall->setArg(0, Object);
6671
Chris Lattner312531a2009-04-12 08:11:20 +00006672
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006673 // Check the argument types.
6674 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006675 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00006676 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006677 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00006678
Douglas Gregor518fda12009-01-13 05:10:00 +00006679 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00006680
6681 OwningExprResult InputInit
6682 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6683 Method->getParamDecl(i)),
6684 SourceLocation(), Owned(Arg));
6685
6686 IsError |= InputInit.isInvalid();
6687 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00006688 } else {
Douglas Gregord47c47d2009-11-09 19:27:57 +00006689 OwningExprResult DefArg
6690 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6691 if (DefArg.isInvalid()) {
6692 IsError = true;
6693 break;
6694 }
6695
6696 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00006697 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006698
6699 TheCall->setArg(i + 1, Arg);
6700 }
6701
6702 // If this is a variadic call, handle args passed through "...".
6703 if (Proto->isVariadic()) {
6704 // Promote the arguments (C99 6.5.2.2p7).
6705 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6706 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00006707 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006708 TheCall->setArg(i + 1, Arg);
6709 }
6710 }
6711
Chris Lattner312531a2009-04-12 08:11:20 +00006712 if (IsError) return true;
6713
Anders Carlssond406bf02009-08-16 01:56:34 +00006714 if (CheckFunctionCall(Method, TheCall.get()))
6715 return true;
6716
Douglas Gregoraa0be172010-04-13 15:50:39 +00006717 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006718}
6719
Douglas Gregor8ba10742008-11-20 16:27:02 +00006720/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00006721/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00006722/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006723Sema::OwningExprResult
6724Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6725 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00006726 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00006727
John McCall5769d612010-02-08 23:07:23 +00006728 SourceLocation Loc = Base->getExprLoc();
6729
Douglas Gregor8ba10742008-11-20 16:27:02 +00006730 // C++ [over.ref]p1:
6731 //
6732 // [...] An expression x->m is interpreted as (x.operator->())->m
6733 // for a class object x of type T if T::operator->() exists and if
6734 // the operator is selected as the best match function by the
6735 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00006736 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00006737 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00006738 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006739
John McCall5769d612010-02-08 23:07:23 +00006740 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00006741 PDiag(diag::err_typecheck_incomplete_tag)
6742 << Base->getSourceRange()))
6743 return ExprError();
6744
John McCalla24dc2e2009-11-17 02:14:36 +00006745 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6746 LookupQualifiedName(R, BaseRecord->getDecl());
6747 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00006748
6749 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00006750 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00006751 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00006752 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00006753 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00006754
6755 // Perform overload resolution.
6756 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006757 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00006758 case OR_Success:
6759 // Overload resolution succeeded; we'll build the call below.
6760 break;
6761
6762 case OR_No_Viable_Function:
6763 if (CandidateSet.empty())
6764 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006765 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006766 else
6767 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006768 << "operator->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006769 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006770 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006771
6772 case OR_Ambiguous:
6773 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00006774 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006775 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006776 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006777
6778 case OR_Deleted:
6779 Diag(OpLoc, diag::err_ovl_deleted_oper)
6780 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00006781 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006782 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006783 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006784 }
6785
John McCall9aa472c2010-03-19 07:35:19 +00006786 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
6787
Douglas Gregor8ba10742008-11-20 16:27:02 +00006788 // Convert the object parameter.
6789 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00006790 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
6791 Best->FoundDecl, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006792 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00006793
6794 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006795 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006796
6797 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00006798 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6799 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00006800 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00006801
6802 QualType ResultTy = Method->getResultType().getNonReferenceType();
6803 ExprOwningPtr<CXXOperatorCallExpr>
6804 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6805 &Base, 1, ResultTy, OpLoc));
6806
6807 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6808 Method))
6809 return ExprError();
6810 return move(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00006811}
6812
Douglas Gregor904eed32008-11-10 20:40:00 +00006813/// FixOverloadedFunctionReference - E is an expression that refers to
6814/// a C++ overloaded function (possibly with some parentheses and
6815/// perhaps a '&' around it). We have resolved the overloaded function
6816/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00006817/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +00006818Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +00006819 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006820 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00006821 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
6822 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00006823 if (SubExpr == PE->getSubExpr())
6824 return PE->Retain();
6825
6826 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6827 }
6828
6829 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00006830 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
6831 Found, Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00006832 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00006833 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00006834 "Implicit cast type cannot be determined from overload");
Douglas Gregor699ee522009-11-20 19:42:02 +00006835 if (SubExpr == ICE->getSubExpr())
6836 return ICE->Retain();
6837
6838 return new (Context) ImplicitCastExpr(ICE->getType(),
6839 ICE->getCastKind(),
6840 SubExpr,
6841 ICE->isLvalueCast());
6842 }
6843
6844 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006845 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00006846 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00006847 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6848 if (Method->isStatic()) {
6849 // Do nothing: static member functions aren't any different
6850 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00006851 } else {
John McCallf7a1a742009-11-24 19:00:30 +00006852 // Fix the sub expression, which really has to be an
6853 // UnresolvedLookupExpr holding an overloaded member function
6854 // or template.
John McCall6bb80172010-03-30 21:47:33 +00006855 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6856 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00006857 if (SubExpr == UnOp->getSubExpr())
6858 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00006859
John McCallba135432009-11-21 08:51:07 +00006860 assert(isa<DeclRefExpr>(SubExpr)
6861 && "fixed to something other than a decl ref");
6862 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6863 && "fixed to a member ref with no nested name qualifier");
6864
6865 // We have taken the address of a pointer to member
6866 // function. Perform the computation here so that we get the
6867 // appropriate pointer to member type.
6868 QualType ClassType
6869 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6870 QualType MemPtrType
6871 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6872
6873 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6874 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00006875 }
6876 }
John McCall6bb80172010-03-30 21:47:33 +00006877 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6878 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00006879 if (SubExpr == UnOp->getSubExpr())
6880 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00006881
Douglas Gregor699ee522009-11-20 19:42:02 +00006882 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6883 Context.getPointerType(SubExpr->getType()),
6884 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00006885 }
John McCallba135432009-11-21 08:51:07 +00006886
6887 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00006888 // FIXME: avoid copy.
6889 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00006890 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00006891 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6892 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00006893 }
6894
John McCallba135432009-11-21 08:51:07 +00006895 return DeclRefExpr::Create(Context,
6896 ULE->getQualifier(),
6897 ULE->getQualifierRange(),
6898 Fn,
6899 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00006900 Fn->getType(),
6901 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00006902 }
6903
John McCall129e2df2009-11-30 22:42:35 +00006904 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00006905 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00006906 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6907 if (MemExpr->hasExplicitTemplateArgs()) {
6908 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6909 TemplateArgs = &TemplateArgsBuffer;
6910 }
John McCalld5532b62009-11-23 01:53:49 +00006911
John McCallaa81e162009-12-01 22:10:20 +00006912 Expr *Base;
6913
6914 // If we're filling in
6915 if (MemExpr->isImplicitAccess()) {
6916 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6917 return DeclRefExpr::Create(Context,
6918 MemExpr->getQualifier(),
6919 MemExpr->getQualifierRange(),
6920 Fn,
6921 MemExpr->getMemberLoc(),
6922 Fn->getType(),
6923 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00006924 } else {
6925 SourceLocation Loc = MemExpr->getMemberLoc();
6926 if (MemExpr->getQualifier())
6927 Loc = MemExpr->getQualifierRange().getBegin();
6928 Base = new (Context) CXXThisExpr(Loc,
6929 MemExpr->getBaseType(),
6930 /*isImplicit=*/true);
6931 }
John McCallaa81e162009-12-01 22:10:20 +00006932 } else
6933 Base = MemExpr->getBase()->Retain();
6934
6935 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00006936 MemExpr->isArrow(),
6937 MemExpr->getQualifier(),
6938 MemExpr->getQualifierRange(),
6939 Fn,
John McCall6bb80172010-03-30 21:47:33 +00006940 Found,
John McCalld5532b62009-11-23 01:53:49 +00006941 MemExpr->getMemberLoc(),
John McCallaa81e162009-12-01 22:10:20 +00006942 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00006943 Fn->getType());
6944 }
6945
Douglas Gregor699ee522009-11-20 19:42:02 +00006946 assert(false && "Invalid reference to overloaded function");
6947 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00006948}
6949
Douglas Gregor20093b42009-12-09 23:02:17 +00006950Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCall161755a2010-04-06 21:38:20 +00006951 DeclAccessPair Found,
Douglas Gregor20093b42009-12-09 23:02:17 +00006952 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +00006953 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +00006954}
6955
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006956} // end namespace clang